package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
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.gson.Gson;
import com.cygnusa.hyperm.adapter.RedeemProductListAdapter;
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.ErrorResponse;
import com.cygnusa.hyperm.wrappers.RedeemCategoryListResponse;
import com.cygnusa.hyperm.wrappers.RedeemProduct;
import com.cygnusa.hyperm.wrappers.RedeemProductResponse;

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

public class RedeemProductListActivity extends AppCompatActivity {
    private RecyclerView redeemList;
    RedeemProductListAdapter adapter;
    TransparentProgressDialog progressDialog;
    ApiService restService;
    private LinearLayoutManager linearLayoutManager;
    RedeemProduct productList = new RedeemProduct();
    TextView header;
    private StorePreference storePreference;
    String cate_id = "";

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

        setContentView(R.layout.activity_redeem_product_list);
        restService = ((MainApplication) getApplication()).getClient();
        redeemList = findViewById(R.id.redeemProductList);
        header = findViewById(R.id.title);
        redeemList.setHasFixedSize(true);
        redeemList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(getBaseContext());
        redeemList.setLayoutManager(linearLayoutManager);

        getCategoryList(true);

        storePreference = new StorePreference(this);

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


    }

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

            restService.getRedeemCategoryList().enqueue(new Callback<RedeemCategoryListResponse>() {
                @Override
                public void onResponse(Call<RedeemCategoryListResponse> call, Response<RedeemCategoryListResponse> response) {

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

                    if (response.body() != null && response.body().getStatus() == 200) {
                        cate_id = response.body().getData().getRoot_category().getCategory_id();
                        redeemList.post(new Runnable() {
                            @Override
                            public void run() {
                                // startActivity(new Intent(RedeemProductListActivity.this, RedeemProductDetailsActivity.class));
                                getProductList(true, cate_id);
                            }
                        });
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        new Handler(HomeActivity.callback).sendEmptyMessage(0);
                        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(RedeemProductListActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(HomeActivity.callback).sendEmptyMessage(0);
                            finish();
                        }
                    }


                }

                @Override
                public void onFailure(Call<RedeemCategoryListResponse> 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();
        }
    }

    protected void onResume() {
        super.onResume();

        if (GlobalData.canLogout) {
            finish();
        }
    }

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

    private void getProductList(boolean canLoadProgress, String cate_id) {
        if (new UtilService().isNetworkAvailable(RedeemProductListActivity.this)) {
            if (canLoadProgress) {
                progressDialog = new TransparentProgressDialog(RedeemProductListActivity.this);
                progressDialog.show();
                // progressBar.setVisibility(View.GONE);
            } else {
                // progressBar.setVisibility(View.VISIBLE);
            }

            restService.getRedeemCategoryProductList(cate_id).enqueue(new Callback<RedeemProductResponse>() {
                @Override
                public void onResponse(Call<RedeemProductResponse> call, Response<RedeemProductResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (response.body() != null && response.body().getStatus() == 200) {
                        productList = response.body().getData();
                        header.setText(productList.getName());
                        adapter = new RedeemProductListAdapter(RedeemProductListActivity.this, productList);
                        redeemList.setAdapter(adapter);

                    } 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 != null)
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            }
                    }


                }

                @Override
                public void onFailure(Call<RedeemProductResponse> 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 void confirmClose() {
        finish();
        RedeemProductListActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }
}
