package com.cygnusa.hyperm;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.adapter.TopicAdapter;
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.MyCallback;
import com.cygnusa.hyperm.util.PositionUpdateListener;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ContentResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.MyContent;
import com.cygnusa.hyperm.wrappers.MyTopic;
import com.cygnusa.hyperm.wrappers.TopicDetailResponse;
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.Callback;
import retrofit2.Response;


public class TopicListActivity extends AppCompatActivity implements PositionUpdateListener {
    ApiService restService;
    TransparentProgressDialog progressDialog;
    EmptyStateRecyclerView topicList;
    TextView title;
    public static MyTopic MY_TOPICS = new MyTopic();
    public static String CATEGORY_ID = "";
    int LAST_CLICKED_POSITION = -1;

    int PAGE = 0;
    int LIMIT = 10;
    TopicAdapter adapter = null;
    ArrayList<MyContent> MY_CONTENT = new ArrayList<>();
    LinearLayoutManager linearLayoutManager;
    int TOTAL_RECORD = 0;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_topic_list);
        setupWindowAnimations();

        restService = ((MainApplication) getApplication()).getClient();
        title = findViewById(R.id.title);
        topicList = findViewById(R.id.topicList);
        topicList.setHasFixedSize(true);
        topicList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(getBaseContext());
        topicList.setLayoutManager(linearLayoutManager);
        title.setText(MY_TOPICS.getTopicname());
        title.setSelected(true);
        topicList.addOnScrollListener(recyclerViewOnScrollListener);
        topicList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(this, "No data available", ""));
        progressBar = findViewById(R.id.progressBar);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);


        topicList.post(new Runnable() {
            @Override
            public void run() {
                getTrainingTopics(true);
            }
        });

        findViewById(R.id.helpIcon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHelpScreen();
            }
        });
    }

    private void showHelpScreen() {
        try {
            View view = null;
            if (adapter != null && adapter.getItemCount() > 0) {
                view = topicList.findViewHolderForAdapterPosition(linearLayoutManager.findFirstVisibleItemPosition()).itemView;
            } else {
                view = topicList;
            }
            new FancyShowCaseView.Builder(this)
                    .focusOn(view)
                    .title("Tap here to view topic contents")
                    .titleSize(22, 1)
                    .closeOnTouch(true)
                    .fitSystemWindows(false)
                    .focusShape(FocusShape.ROUNDED_RECTANGLE)
                    .backgroundColor(Color.parseColor("#99000000"))
                    .build()
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    private void getTrainingTopics(boolean canLoadProgress) {
        if (new UtilService().isNetworkAvailable(TopicListActivity.this)) {
            if (canLoadProgress) {
                progressDialog = new TransparentProgressDialog(TopicListActivity.this);
                progressDialog.show();
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }

            restService.getTopicContents(MY_TOPICS.getAssettopicid(), PAGE, LIMIT).enqueue(new Callback<ContentResponse>() {
                @Override
                public void onResponse(Call<ContentResponse> call, Response<ContentResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    progressBar.setVisibility(View.GONE);

                    if (response.body() != null && response.body().getStatus() == 200) {
                        TOTAL_RECORD = Integer.parseInt(response.body().getTotal());
                        if (adapter == null) {
                            MY_CONTENT = response.body().getData();

                            adapter = new TopicAdapter(TopicListActivity.this, MY_CONTENT, CATEGORY_ID, TopicListActivity.this);
                            topicList.setAdapter(adapter);
                        } else {
                            MY_CONTENT.addAll(response.body().getData());
                            adapter.notifyDataSetChanged();
                        }

                        if (MY_CONTENT.size() == 0) {
                            topicList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                        } else {
                            topicList.invokeState(EmptyStateRecyclerView.STATE_OK);
                        }
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    } else if (response.body() != null) {
                        GlobalData.showToast(getBaseContext(), 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(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        }
                    }

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

                @Override
                public void onFailure(Call<ContentResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    progressBar.setVisibility(View.GONE);
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }


    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) {
                    PAGE++;
                    getTrainingTopics(false);
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (LAST_CLICKED_POSITION != -1) {
            if (!MY_CONTENT.get(LAST_CLICKED_POSITION).getStatus().trim().equalsIgnoreCase("2")) {
                getTopicByPosition(LAST_CLICKED_POSITION);
            }
            LAST_CLICKED_POSITION = -1;
        }
        if (GlobalData.canLogout) {
            finish();
        }
    }

    private void getTopicByPosition(int position) {
        if (new UtilService().isNetworkAvailable(TopicListActivity.this)) {
            restService.getTopicDetail(MY_CONTENT.get(position).getContentid())
                    .enqueue(new MyCallback<TopicDetailResponse>(position) {
                        @Override
                        public void onResponse(Call<TopicDetailResponse> call, Response<TopicDetailResponse> response) {
                            if (response.body() != null && response.body().getStatus() == 200) {
                                if (response.body().getData() != null) {
                                    MY_CONTENT.get(id).setStatus(response.body().getData().getTopic_status());
                                    adapter.notifyDataSetChanged();
                                }
                            } else if (response.body() != null && response.body().getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            } else if (response.errorBody() != null) {
                                Gson gson = new Gson();
                                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                                if (message.getStatus() == 401) {
                                    GlobalData.canLogout = true;
                                    finish();
                                }
                            }
                        }

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

                        }
                    });
        }
    }

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

}