package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
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.google.firebase.analytics.FirebaseAnalytics;
import com.google.gson.Gson;
import com.cygnusa.hyperm.adapter.BulletinAdapter;
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.Bulletin;
import com.cygnusa.hyperm.wrappers.BulletinResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
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 BulletinActivity extends AppCompatActivity {
    ApiService restService;
    TransparentProgressDialog progressDialog;
    EmptyStateRecyclerView bulletinList;
    TextView title;
    ProgressBar progressBar;
    LinearLayoutManager linearLayoutManager;
    BulletinAdapter adapter = null;
    int TOTAL_RECORD = 0;
    int PAGE = 0;
    public static boolean isFromAMHome = false;
    int LIMIT = 10;
    ArrayList<Bulletin> MY_CONTENTS = new ArrayList<>();
    public Bulletin Bulletin = new Bulletin();
    private FirebaseAnalytics firebaseAnalytics;

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

        setContentView(R.layout.activity_bulletin);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));
        firebaseAnalytics = FirebaseAnalytics.getInstance(this);
        restService = ((MainApplication) getApplication()).getClient();
        title = findViewById(R.id.title);
        bulletinList = findViewById(R.id.topicList);
        bulletinList.setHasFixedSize(true);
        bulletinList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(getBaseContext());
        bulletinList.setLayoutManager(linearLayoutManager);
        bulletinList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(this, "No data available", ""));
        title.setText("Bulletin");
        bulletinList.addOnScrollListener(recyclerViewOnScrollListener);
        progressBar = findViewById(R.id.progressBar);

        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);
        bulletinList.post(new Runnable() {
            @Override
            public void run() {
                getBulletinContents(true);
            }
        });

        findViewById(R.id.helpIcon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  showHelpScreen();
            }
        });
        Bundle bundle = new Bundle();
        /*bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "1");
        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "BulletinActivity");
        //bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/

    }

    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++;
                    getBulletinContents(false);
                }
            }
        }
    };

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

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

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (isFromAMHome) {
            startActivity(new Intent(BulletinActivity.this, AMHomeActivity.class));
            finish();
        }
    }

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

    private void showHelpScreen() {
        try {
            View view;
            if (adapter != null && adapter.getItemCount() > 0) {
                view = bulletinList.findViewHolderForAdapterPosition(linearLayoutManager.findFirstVisibleItemPosition()).itemView;
            } else {
                view = bulletinList;
            }
            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();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            confirmClose();
        }
        return super.onOptionsItemSelected(item);
    }

    private void confirmClose() {
        if (isFromAMHome) {
            startActivity(new Intent(BulletinActivity.this, AMHomeActivity.class));
        }
        finish();
        BulletinActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

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

            restService.getBulletinContents(PAGE, LIMIT).enqueue(new Callback<BulletinResponse>() {
                @Override
                public void onResponse(Call<BulletinResponse> call, Response<BulletinResponse> 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();
                            adapter = new BulletinAdapter(BulletinActivity.this, MY_CONTENTS);
                            bulletinList.setAdapter(adapter);
                        } else {
                            MY_CONTENTS.addAll(response.body().getData());

                        }

                        if (MY_CONTENTS.size() == 0) {
                            bulletinList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                        } else {
                            bulletinList.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<BulletinResponse> 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();
        }
    }

}
