package com.cygnusa.hyperm.fragments;


import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
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 android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;

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.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AssessmentList;
import com.cygnusa.hyperm.wrappers.AssessmentListResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.FragmentItem;
import com.cygnusa.hyperm.wrappers.MyTraining;
import com.cygnusa.hyperm.wrappers.TrainingCategory;

import java.util.ArrayList;

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

public class AssessmentFragment extends Fragment implements DismissListener {

    View mainView;

    ViewPager myAssessmentPager;
    SmartTabLayout myAssessmentPagerTab;
    TransparentProgressDialog progressDialog;
    ApiService restService;
    ArrayList<AssessmentList> MY_ASSESSMENTS = new ArrayList<>();
    ArrayList<FragmentItem> fragments = new ArrayList<>();
    private int SHOWCASE_POSITION = 0;
    public static Handler.Callback callback;

    public AssessmentFragment() {

    }

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

    @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();
        myAssessmentPager = mainView.findViewById(R.id.myTrainingPager);
        myAssessmentPagerTab = mainView.findViewById(R.id.myTrainingPagerTab);
        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                getAssement();
                return false;
            }
        };

//        assessmentSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                setAssementCategory(position);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//
//            }
//        });

    }



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

            try {
                restService.getAssement().enqueue(new Callback<AssessmentListResponse>() {
                    @Override
                    public void onResponse(Call<AssessmentListResponse> call, Response<AssessmentListResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (response.body() != null && response.body().getStatus() == 200) {
                            MY_ASSESSMENTS = response.body().getData();
                            if (MY_ASSESSMENTS == null) {
                                MY_ASSESSMENTS = new ArrayList<>();
                            }
                            GlobalData.sdb.delete("training", null, null);
                            Gson gson = new Gson();
                            JsonElement jsonElement = gson.toJsonTree(
                                    MY_ASSESSMENTS, new TypeToken<ArrayList<AssessmentList>>() {
                                    }.getType());
                            ContentValues values = new ContentValues();
                            values.put("training", jsonElement.toString());
                            GlobalData.sdb.insert("training", null, values);
                            setAssessment();
                        } 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("AssessmentFragment", true)) {
//                                    showHelpScreen();
//                                    getActivity().getPreferences(MODE_PRIVATE)
//                                            .edit().putBoolean("AssessmentFragment", false).apply();
//                                }
//                            }
//                        }, 1000);

                    }

                    @Override
                    public void onFailure(Call<AssessmentListResponse> 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 {
            Cursor cursor = GlobalData.sdb.rawQuery("select * from training", null);
            if (cursor.getCount() != 0) {
                cursor.moveToFirst();
                Gson gson = new Gson();
                MY_ASSESSMENTS = gson.fromJson(
                        cursor.getString(cursor.getColumnIndex("training")),
                        new TypeToken<ArrayList<MyTraining>>() {
                        }.getType());
                setAssessment();
            } else {
                GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void setAssessment() {
        ArrayList<String> trainingSpinnerList = new ArrayList<>();
        for (AssessmentList training : MY_ASSESSMENTS) {
           // trainingSpinnerList.add(training.getCoursename());
        }

        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<>(getActivity(),
                R.layout.spinner_item, trainingSpinnerList);
        spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
       // assessmentSpinner.setAdapter(spinnerArrayAdapter);
    }

    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(myAssessmentPagerTab)
                        .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) {
                AssessmentListFragment fr = (AssessmentListFragment) fragments
                        .get(myAssessmentPager.getCurrentItem()).getFragment();
                View view = fr.getFirstRow();
                new FancyShowCaseView.Builder(getActivity())
                        .focusOn(view)
                        .title("Tap here attend assessment")
                        .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;
        String trainingId;

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

        @Override
        public Fragment getItem(int position) {
            AssessmentListFragment fragment = new AssessmentListFragment();
            fragment.setCategory(categories.get(position));
            fragment.setTrainingId(trainingId);
            FragmentItem item = new FragmentItem();
            item.setFragment(fragment);
            item.setTitle(categories.get(position).getCatename());
            fragments.add(item);

            return fragment;
        }

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


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