package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.adapter.TrainingAdapter;
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.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.MyTopic;
import com.cygnusa.hyperm.wrappers.TopicResponse;
import com.cygnusa.hyperm.wrappers.TrainingCategory;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import java.util.ArrayList;

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

public class CategoryFragment extends Fragment implements PositionUpdateListener {

    View mainView;
    ApiService restService;
    ArrayList<MyTopic> MY_TOPICS = new ArrayList<>();
    EmptyStateRecyclerView categoryList;
    TrainingCategory category;
    int LAST_CLICKED_POSITION = -1;
    TrainingAdapter adapter;
    Context context;
    LinearLayoutManager linearLayoutManager;

    int PAGE = 0;
    int LIMIT = 10;
    int TOTAL_RECORD = 0;
    ProgressBar progressBar;
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;

    public CategoryFragment() {

    }

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

    public void onResumeFragment() {
        context = getActivity();
        if (LAST_CLICKED_POSITION != -1) {
            getCategory();
            LAST_CLICKED_POSITION = -1;
        }
        // getCategory();
    }

    @SuppressLint("StaticFieldLeak")
    private void getCategory() {
        if (new UtilService().isNetworkAvailable(getActivity())) {
            try {
                restService.getTrainingTopics(category.getCateid(), PAGE, LIMIT)
                        .enqueue(new MyCallback<TopicResponse>() {
                            @Override
                            public void onResponse(Call<TopicResponse> call, Response<TopicResponse> response) {
                                if (response.body() != null && response.body().getStatus() == 200) {
                                    MY_TOPICS = response.body().getData();
                                    if (MY_TOPICS == null) {
                                        MY_TOPICS = new ArrayList<>();
                                    }
                                    setTopicCategory();
                                    if (MY_TOPICS.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<TopicResponse> call, Throwable t) {
                                GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                            }
                        });

            } catch (Exception e) {
                GlobalData.showToast(getActivity(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
            }
        } else {
            Cursor cursor = GlobalData.sdb.rawQuery("select * from topic where" + " category_id='"
                    + category.getCateid() + "'", null);
            MY_TOPICS = new ArrayList<>();
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                Gson gson = new Gson();
                for (int i = 0; i < cursor.getCount(); i++) {
                    MyTopic myTopic = gson.fromJson(
                            cursor.getString(cursor.getColumnIndex("topic")),
                            new TypeToken<MyTopic>() {
                            }.getType());
                    MY_TOPICS.add(myTopic);
                    cursor.moveToNext();

                }
                setTopicCategory();
            } else {
                GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
            }
            if (MY_TOPICS.size() == 0) {
                categoryList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
            } else {
                categoryList.invokeState(EmptyStateRecyclerView.STATE_OK);
            }
        }
    }

    private RecyclerView.OnScrollListener recyclerViewOnScrollListener = new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int visibleItemCount = linearLayoutManager.getChildCount();
            int totalItemCount = linearLayoutManager.getItemCount();
            int firstVisibleItemPosition = linearLayoutManager.findFirstVisibleItemPosition();

            if (progressBar.getVisibility() != View.VISIBLE) {
                if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount < TOTAL_RECORD && MY_TOPICS.size() < TOTAL_RECORD) {
                    PAGE++;
                    getCategory();
                }
            }
        }
    };

    private void setTopicCategory() {
        adapter = new TrainingAdapter(context, MY_TOPICS, category);
        categoryList.setAdapter(adapter);
        if (MY_TOPICS == null || MY_TOPICS.size() == 0) {
            categoryList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
        } else {
            categoryList.invokeState(EmptyStateRecyclerView.STATE_OK);
        }
    }

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

    @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;
        context = getActivity();
        restService = ((MainApplication) getActivity().getApplication()).getClient();
        categoryList = mainView.findViewById(R.id.categoryList);

        categoryList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(getActivity());
        categoryList.setLayoutManager(linearLayoutManager);
        progressBar = mainView.findViewById(R.id.progressBar);
        categoryList.setLayoutManager(linearLayoutManager);
        categoryList.addOnScrollListener(recyclerViewOnScrollListener);
        categoryList.setHasFixedSize(true);
        categoryList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(getActivity(), "No data available", ""));
        mViewCreated = true;
        onViewCreatedFirstSight();

    }

    @SuppressLint("StaticFieldLeak")
    private void onViewCreatedFirstSight() {
        if (mUserSeen && mViewCreated) {
            getCategory();
        }
    }


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