package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.database.Cursor;
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.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.adapter.AssessmentListAdapter;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.PositionUpdateListener;
import com.cygnusa.hyperm.util.StorePreference;
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.AssessmentStatusResponse;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.HitCountModel;
import com.cygnusa.hyperm.wrappers.TrainingCategory;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import java.util.ArrayList;
import java.util.Objects;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AssessmentListFragment extends Fragment implements PositionUpdateListener {

    View mainView;
    ApiService restService;
    TrainingCategory category;
    EmptyStateRecyclerView categoryList;
    String TRAINING_ID = "";
    int LAST_CLICKED_POSITION = -1;
    AssessmentListAdapter adapter;
    TransparentProgressDialog progressDialog;
    ArrayList<AssessmentList> ASSESSMENT_LIST = new ArrayList<>();
    ArrayList<AssessmentList> OFFLINE_ASSESSMENT_LIST = new ArrayList<>();
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;
    LinearLayoutManager linearLayoutManager;
    public static Handler.Callback callback;

    public AssessmentListFragment() {

    }

    public void onResumeFragment() {
        if (LAST_CLICKED_POSITION != -1) {
            getAssessmentListByCategory();
            LAST_CLICKED_POSITION = -1;
        }
    }

    private void getAssessmentByPosition(int position) {
        if (new UtilService().isNetworkAvailable(getActivity())) {
            restService.getAssessmentByPosition(ASSESSMENT_LIST.get(position).getAssessmentid())
                    .enqueue(new MyCallback<AssessmentStatusResponse>(position) {
                        @Override
                        public void onResponse(Call<AssessmentStatusResponse> call, Response<AssessmentStatusResponse> response) {
                            if (response.body() != null && response.body().getStatus() == 200) {
                                if (response.body().getData() != null) {
                                    ASSESSMENT_LIST.remove(id);
                                    ASSESSMENT_LIST.add(id, response.body().getData());
                                    adapter.notifyDataSetChanged();
                                }
                            } else if (response.body() != null && response.body().getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(HomeActivity.callback).sendEmptyMessage(0);
                            } 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);
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<AssessmentStatusResponse> call, Throwable t) {

                        }
                    });
        }
    }

    public void setCategory(TrainingCategory trainingCategory) {
        this.category = trainingCategory;
    }

    public void setTrainingId(String id) {
        this.TRAINING_ID = id;
    }

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        restService = ((MainApplication) getActivity().getApplication()).getClient();
        categoryList = mainView.findViewById(R.id.categoryList);
        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                getAssessmentListByCategory();
                return false;
            }
        };
        mViewCreated = true;
        onViewCreatedFirstSight();

        if (StorePreference.getInstance(getActivity()).getBooleanValue(GlobalData.ISDSELOGIN))
            sendFirstHitCountToServer();
    }


    private void sendFirstHitCountToServer() {
        restService.sendAllHitCount(buildFirstConfigData()).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 buildFirstConfigData() {
        HitCountModel hitCountModel = new HitCountModel();
        hitCountModel.setPage("Assessment");
        hitCountModel.setViewtime("0");
        return hitCountModel;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mViewCreated = false;
        mUserSeen = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!mUserSeen && isVisibleToUser) {
            mUserSeen = true;
            onViewCreatedFirstSight();
        }
    }


    @SuppressLint("StaticFieldLeak")
    private void onViewCreatedFirstSight() {
        if (mUserSeen && mViewCreated) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();

            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    try {
                        Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment where category_id='"
                                + category.getCateid() + "' and training_id='" + TRAINING_ID + "'", null);
                        OFFLINE_ASSESSMENT_LIST = new ArrayList<>();
                        if (cursor.getCount() != 0) {
                            cursor.moveToFirst();
                            for (int i = 0; i < cursor.getCount(); i++) {
                                Gson gson = new Gson();
                                AssessmentList assessmentList = gson.fromJson(
                                        cursor.getString(cursor.getColumnIndex("assessment")),
                                        new TypeToken<AssessmentList>() {
                                        }.getType());
                                OFFLINE_ASSESSMENT_LIST.add(assessmentList);
                                cursor.moveToNext();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    getAssessmentListByCategory();
                }
            }.execute();
        }
    }
    private void setAssessmentList() {
        try {
            adapter = new AssessmentListAdapter(getActivity(), ASSESSMENT_LIST, TRAINING_ID,
                    AssessmentListFragment.this, restService, false, OFFLINE_ASSESSMENT_LIST);
            categoryList.setHasFixedSize(true);
            categoryList.setItemAnimator(new SlideInLeftAnimator());
            linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            categoryList.setLayoutManager(linearLayoutManager);
            categoryList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                    new TextStateDisplay(Objects.requireNonNull(getActivity()), "No data available", ""));
            categoryList.setAdapter(adapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getAssessmentListByCategory() {

        if (new UtilService().isNetworkAvailable(getActivity())) {
            try {
                restService.getAssessmentList().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) {
                            ASSESSMENT_LIST = response.body().getData();

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

                            if (ASSESSMENT_LIST.size() == 0) {
                                categoryList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                            } else {
                                categoryList.invokeState(EmptyStateRecyclerView.STATE_OK);
                            }

                        } 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);
                            }
                        }
                    }

                    @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 {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            if (OFFLINE_ASSESSMENT_LIST.size() > 0) {
                adapter = new AssessmentListAdapter(getActivity(), OFFLINE_ASSESSMENT_LIST, TRAINING_ID,
                        AssessmentListFragment.this, restService,  true, OFFLINE_ASSESSMENT_LIST);
                categoryList.setAdapter(adapter);
                if (ASSESSMENT_LIST.size() == 0 && OFFLINE_ASSESSMENT_LIST.size() == 0) {
                    categoryList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                } else {
                    categoryList.invokeState(EmptyStateRecyclerView.STATE_OK);
                }
            } else {
                GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPositionUpdate(int position) {
        LAST_CLICKED_POSITION = position;
    }

    public View getFirstRow() {
        if (adapter.getItemCount() > 0) {
            return categoryList.findViewHolderForAdapterPosition(linearLayoutManager.findFirstVisibleItemPosition()).itemView;
        } else {
            return categoryList;
        }
    }
}
