package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.cygnusa.hyperm.adapter.ContentAdapter;
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.StorePreference;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ContentResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.HitCountModel;
import com.cygnusa.hyperm.wrappers.MyContent;
import com.cygnusa.hyperm.wrappers.MyTopic;
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 java.util.Calendar;

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


public class ContentListActivity extends AppCompatActivity {
    ApiService restService;
    TransparentProgressDialog progressDialog;
    EmptyStateRecyclerView topicList;
    TextView title;
    public static MyTopic TOPIC = new MyTopic();
    int PAGE = 0;
    int LIMIT = 10;
    ContentAdapter adapter = null;

    ArrayList<MyContent> FILTER_CONTENTS = new ArrayList<>();

    LinearLayoutManager linearLayoutManager;
    int TOTAL_RECORD = 0;
    ArrayList<MyContent> MY_CONTENTS = new ArrayList<>();
    ProgressBar progressBar;
    EditText contentSearch;
    public static TrainingCategory TRAINING_ID;
    private StorePreference storePreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_list);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));
        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);
        topicList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(this, "No data available", ""));
        topicList.addOnScrollListener(recyclerViewOnScrollListener);
        title.setText(TOPIC.getTopicname());
        storePreference = new StorePreference(this);
        title.setSelected(true);
        topicList.addOnScrollListener(recyclerViewOnScrollListener);
        progressBar = findViewById(R.id.progressBar);
        contentSearch = findViewById(R.id.contentSearch);
        contentSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                doFilter();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
        topicList.post(new Runnable() {
            @Override
            public void run() {
                getTopicContents(true);
            }
        });
        findViewById(R.id.helpIcon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHelpScreen();
            }
        });
        if (StorePreference.getInstance(this).getBooleanValue(GlobalData.ISDSELOGIN))
            sendHitCountToServer();
    }


    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(TOPIC.getCateid()));
        hitCountModel.setAssettopicid(Integer.valueOf(TOPIC.getAssettopicid()));
        hitCountModel.setViewtime("0");
        return hitCountModel;
    }

    private void showHelpScreen() {
        try {
            View view;
            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 the PDF or Video")
                    .titleSize(22, 1)
                    .closeOnTouch(true)
                    .fitSystemWindows(false)
                    .focusShape(FocusShape.ROUNDED_RECTANGLE)
                    .backgroundColor(Color.parseColor("#99000000"))
                    .build()
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doFilter() {
        FILTER_CONTENTS.clear();
        for (int i = 0; i < MY_CONTENTS.size(); i++) {
            if (MY_CONTENTS.get(i).getTitle().trim().toLowerCase().contains(contentSearch.getText().toString().toLowerCase().trim()) ||
                    MY_CONTENTS.get(i).getDescription().trim().toLowerCase().contains(contentSearch.getText().toString().trim().toLowerCase()) ||
                    MY_CONTENTS.get(i).getContent_files().get(0).getFiletype().trim().toLowerCase().contains(contentSearch.getText().toString().trim().toLowerCase()))
                FILTER_CONTENTS.add(MY_CONTENTS.get(i));
        }
        adapter.notifyDataSetChanged();
    }

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

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        if (GlobalData.canLogout) {
            finish();
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void getTopicContents(boolean canLoadProgress) {
        if (new UtilService().isNetworkAvailable(ContentListActivity.this)) {
            if (canLoadProgress) {
                progressDialog = new TransparentProgressDialog(ContentListActivity.this);
                progressDialog.show();
                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.VISIBLE);
            }

            restService.getTopicContents(TOPIC.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_CONTENTS = response.body().getData();
                            setContentList();
                        } else {
                            MY_CONTENTS.addAll(response.body().getData());
                            doFilter();
                        }

                        if (MY_CONTENTS.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("ContentListActivity", true)) {
                                showHelpScreen();
                                getPreferences(MODE_PRIVATE).edit().putBoolean("ContentListActivity", 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 {

            Cursor cursor = GlobalData.sdb.rawQuery("select * from topic_content where" + " category_id='"
                    + TRAINING_ID.getCateid() +
                    "' and topic_id='" + TOPIC.getAssettopicid() + "'", null);

            MY_CONTENTS = new ArrayList<>();
            if (cursor.getCount() > 0) {
                cursor.moveToFirst();
                Gson gson = new Gson();
                for (int i = 0; i < cursor.getCount(); i++) {
                    MyContent myContent = gson.fromJson(
                            cursor.getString(cursor.getColumnIndex("topic_content")),
                            new TypeToken<MyContent>() {
                            }.getType());
                    MY_CONTENTS.add(myContent);
                    cursor.moveToNext();
                }
                setContentList();
            } else {
                GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void setContentList() {
        FILTER_CONTENTS.addAll(MY_CONTENTS);
        adapter = new ContentAdapter(ContentListActivity.this, FILTER_CONTENTS, TOPIC, TRAINING_ID);
        topicList.setAdapter(adapter);
    }

    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_CONTENTS.size() < TOTAL_RECORD) {
                    PAGE++;
                    getTopicContents(false);
                }
            }
        }
    };

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(ContentListActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}