package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.fancyshowcase.DismissListener;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.DepthPageTransformerNew;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.FragmentItem;
import com.cygnusa.hyperm.wrappers.HitCountModel;
import com.cygnusa.hyperm.wrappers.MyTrainingResponse;
import com.cygnusa.hyperm.wrappers.TrainingCategory;

import java.util.ArrayList;
import java.util.Calendar;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.content.Context.MODE_PRIVATE;

public class MyLearningFragment extends Fragment implements DismissListener {

  View mainView;
  ViewPager myTrainingPager;
  SmartTabLayout myTrainingPagerTab;
  TransparentProgressDialog progressDialog;
  ApiService restService;
  ArrayList<TrainingCategory> MY_TRAININGS;

  ArrayList<FragmentItem> fragments = new ArrayList<>();

  public static Handler.Callback callback;
  private int SHOWCASE_POSITION = 0;
  public static boolean isOffline = false;
  private String pageTitle = "";
  private int selectedPosition;
  private StorePreference storePreference;

  public MyLearningFragment() {

  }

  public void onResumeFragment() {
    try {
      if (myTrainingPager != null) {
        CategoryFragment fragment = (CategoryFragment) fragments.get(myTrainingPager.getCurrentItem()).getFragment();
        fragment.onResumeFragment();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

   // getMyTraining();
  }

  @Override
  public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_my_training, container, false);
  }

  @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mainView = view;
    restService = ((MainApplication) getActivity().getApplication()).getClient();

    myTrainingPager = mainView.findViewById(R.id.myTrainingPager);
    myTrainingPagerTab = mainView.findViewById(R.id.myTrainingPagerTab);
    storePreference = new StorePreference(getActivity());


    callback = new Handler.Callback() {
      @Override
      public boolean handleMessage(Message msg) {

       getMyTraining();
        return false;
      }
    };

    myTrainingPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

      }

      @Override
      public void onPageSelected(int position) {
        Log.e("title", MY_TRAININGS.get(position).getCatename());
        pageTitle = MY_TRAININGS.get(position).getCatename();
        selectedPosition = position;
        storePreference.setString(GlobalData.PAGETITLE,pageTitle);
        if (StorePreference.getInstance(getActivity()).getBooleanValue(GlobalData.ISDSELOGIN))
          sendHitCountToServer();
      }

      @Override
      public void onPageScrollStateChanged(int state) {

      }
    });


  }


  private void sendHitCountToServer() {
    restService.sendAllHitCount(buildConfigData()).enqueue(new Callback<CommonResponse>() {
      @Override
      public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
        if (response.body() != null) {

          Log.e("responeHit", response.body().getMessage());
        } else {
          Log.e("responeHit", response.body().getMessage());
        }
      }

      @Override
      public void onFailure(Call<CommonResponse> call, Throwable t) {
        if (t.getMessage() != null) {
          Log.e("responeHit", t.getMessage());
        }
      }
    });
  }

  private HitCountModel buildConfigData() {
    Calendar calendar = Calendar.getInstance();
    HitCountModel hitCountModel = new HitCountModel();
    hitCountModel.setPage("Learning");
    hitCountModel.setCateid(Integer.valueOf(MY_TRAININGS.get(selectedPosition).getCateid()));
    hitCountModel.setViewtime("0");
    return hitCountModel;
  }


  @SuppressLint("StaticFieldLeak")
  private void getMyTraining() {

    if (new UtilService().isNetworkAvailable(getActivity())) {
      progressDialog = new TransparentProgressDialog(getActivity());
      progressDialog.show();

      try {
        restService.getMyTraining().enqueue(new Callback<MyTrainingResponse>() {
          @Override
          public void onResponse(Call<MyTrainingResponse> call, Response<MyTrainingResponse> response) {
            if (progressDialog != null && progressDialog.isShowing()) {
              progressDialog.dismiss();
            }

            if (response.body() != null && response.body().getStatus() == 200) {
              MY_TRAININGS = response.body().getData();

              if (MY_TRAININGS == null) {
                MY_TRAININGS = new ArrayList<>();
              }

              GlobalData.sdb.delete("training_category", null, null);
              Gson gson = new Gson();

              JsonElement jsonElement = gson.toJsonTree(
                      MY_TRAININGS, new TypeToken<ArrayList<TrainingCategory>>() {
                      }.getType());
              ContentValues values = new ContentValues();
              values.put("training_category", jsonElement.toString());
              GlobalData.sdb.insert("training_category", null, values);
              setTrainingCategory();
              pageTitle = MY_TRAININGS.get(0).getCatename();
              storePreference.setString(GlobalData.PAGETITLE,pageTitle);
              if (StorePreference.getInstance(getActivity()).getBooleanValue(GlobalData.ISDSELOGIN))
                sendHitCountToServer();
            } else if (response.body() != null && response.body().getStatus() == 401) {
              GlobalData.canLogout = true;
              new Handler(HomeActivity.callback).sendEmptyMessage(0);
            } else if (response.body() != null) {
              GlobalData.showToast(getActivity(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
            } else if (response.errorBody() != null) {
              Gson gson = new Gson();
              ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
              GlobalData.showToast(getActivity(), message.getMessage(), Toast.LENGTH_SHORT).show();
              if (message.getStatus() == 401) {
                GlobalData.canLogout = true;
                new Handler(HomeActivity.callback).sendEmptyMessage(0);
              }
            }

            new Handler().postDelayed(new Runnable() {
              @Override
              public void run() {
                if (getActivity().getPreferences(MODE_PRIVATE).getBoolean("MyTrainingFragment", true)) {
                  //showHelpScreen();
                  getActivity().getPreferences(MODE_PRIVATE)
                          .edit().putBoolean("MyTrainingFragment", false).apply();
                }
              }
            }, 1000);

          }

          @Override
          public void onFailure(Call<MyTrainingResponse> call, Throwable t) {
            if (progressDialog != null && progressDialog.isShowing()) {
              progressDialog.dismiss();
            }

            GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
          }
        });

      } catch (Exception e) {
        if (progressDialog != null && progressDialog.isShowing()) {
          progressDialog.dismiss();
        }

        GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
      }
    } else {
      new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {
          try {
            Cursor cursor = GlobalData.sdb.rawQuery("select * from training_category", null);
            MY_TRAININGS = new ArrayList<>();
            if (cursor.getCount() != 0) {
              cursor.moveToFirst();
              Gson gson = new Gson();
              MY_TRAININGS = gson.fromJson(
                      cursor.getString(cursor.getColumnIndex("training_category")),
                      new TypeToken<ArrayList<TrainingCategory>>() {
                      }.getType());
            }
          } catch (Exception e) {
            e.printStackTrace();
          }
          return null;
        }

        @Override
        protected void onPostExecute(String s) {
          super.onPostExecute(s);
          if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
          }
          if (MY_TRAININGS.size() == 0) {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
          }
          setTrainingCategory();
        }
      }.execute();
    }
  }

  private void setTrainingCategory() {
    myTrainingPager.setPageTransformer(true, new DepthPageTransformerNew());
    myTrainingPager.setAdapter(new CategoryAdapter(getChildFragmentManager(),
            new ArrayList<TrainingCategory>()));
    myTrainingPager.setAdapter(new CategoryAdapter(getChildFragmentManager(), MY_TRAININGS));
    myTrainingPagerTab.setViewPager(myTrainingPager);
    myTrainingPager.setOffscreenPageLimit(MY_TRAININGS.size());
  }


  public void showHelpScreen() {
    try {
      SHOWCASE_POSITION = 0;
      new FancyShowCaseView.Builder(getActivity())

              .title("Tap here to select the category")
              .titleSize(22, 1)
              .closeOnTouch(true)
              .focusShape(FocusShape.ROUNDED_RECTANGLE)
              .dismissListener(this)
              .backgroundColor(Color.parseColor("#99000000"))
              .build()
              .show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onDismiss(String id) {
    try {
      if (SHOWCASE_POSITION == 0) {
        new FancyShowCaseView.Builder(getActivity())
                .focusOn(myTrainingPagerTab)
                .title("Tap or swipe to navigate to next page")
                .titleSize(22, 1)
                .closeOnTouch(true)
                .focusShape(FocusShape.ROUNDED_RECTANGLE)
                .dismissListener(this)
                .backgroundColor(Color.parseColor("#99000000"))
                .build()
                .show();
      } else if (SHOWCASE_POSITION == 1) {
        CategoryFragment fr = (CategoryFragment) fragments.get(myTrainingPager.getCurrentItem()).getFragment();
        View view = fr.getFirstRow();
        new FancyShowCaseView.Builder(getActivity())
                .focusOn(view)
                .title("Tap to view the content")
                .titleSize(22, 1)
                .closeOnTouch(true)
                .focusShape(FocusShape.ROUNDED_RECTANGLE)
                .dismissListener(this)
                .backgroundColor(Color.parseColor("#99000000"))
                .build()
                .show();
      }
      SHOWCASE_POSITION++;
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onSkipped(String id) {

  }

  public class CategoryAdapter extends FragmentStatePagerAdapter {

    ArrayList<TrainingCategory> categories;

    private CategoryAdapter(FragmentManager fm, ArrayList<TrainingCategory> list) {
      super(fm);
      categories = list;
      fragments = new ArrayList<>();
    }

    @Override
    public Fragment getItem(int position) {
      CategoryFragment fragment = new CategoryFragment();
      fragment.setCategory(categories.get(position));
      FragmentItem item = new FragmentItem();
      item.setFragment(fragment);
      item.setTitle(String.valueOf(categories.get(position)));
      fragments.add(item);
      return fragment;
    }

    @Override
    public int getCount() {
      return categories.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
      return categories.get(position).getCatename();
    }
  }
}