package com.cygnusa.hyperm;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.adapter.ProductListAdapter;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CommonMethods;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllExploreImageList;
import com.cygnusa.hyperm.wrappers.GetAllExploreModel;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProductWelcomeScreenActivity extends AppCompatActivity implements View.OnClickListener {
    ApiService restService;
    private GridView gridView;
    private ProductListAdapter productAdapter;
    String selectedModel = "1";
    ProgressBar progressBar;
    StorePreference storePreference;
    List<GetAllExploreImageList> listData = new ArrayList<>();
    private ImageView img_close, img_broucher, img_rating;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        restService = ((MainApplication) getApplication()).getClient();
        initViews();
    }
    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }
    private void initViews() {
        progressBar = findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        img_close = findViewById(R.id.img_close);
        img_close.setOnClickListener(this);
        img_broucher = findViewById(R.id.imgBroucher);
        img_broucher.setOnClickListener(this);
        img_rating = findViewById(R.id.img_rating);
        img_rating.setOnClickListener(this);
        gridView = (GridView) findViewById(R.id.gridView);
        storePreference = new StorePreference(this);
        storePreference.setString(GlobalData.SELECTED_MODEL, selectedModel);
        setupWindowAnimations();
        if (CommonMethods.isNetworkAvailable(this)) {
            getAllExploreImageDataList();
        } else {
            checkLocalExplorerFile();
        }
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                if(position==listData.size()){

                }else {
                    Intent intent = new Intent(ProductWelcomeScreenActivity.this, ProductExplorerActivity.class);
                    storePreference.setString(GlobalData.SELECTED_MODEL_NAME, listData.get(position).getModelName());
                    storePreference.setString(GlobalData.SELECTED_MODEL, listData.get(position).getModelId());
                    storePreference.setInt(GlobalData.SELECTID, position);
                    startActivity(intent);
                }
            }
        });
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            startActivity(new Intent(this, ProductExploreDetailsActivity.class));
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public void onBackPressed() {
        if (GlobalData.user.getData().getRole().equalsIgnoreCase("16")) {
            startActivity(new Intent(ProductWelcomeScreenActivity.this, ProductExploreDetailsActivity.class));
            finish();
        } else {
            super.onBackPressed();
        }
    }
    private void getAllExploreImageDataList() {
        progressBar.setVisibility(View.VISIBLE);
        restService.getAllExploreImage().enqueue(new Callback<GetAllExploreModel>() {
            @Override
            public void onResponse(@NonNull Call<GetAllExploreModel> call, @NonNull Response<GetAllExploreModel> response) {
                progressBar.setVisibility(View.GONE);
                SharedPreferences pref = getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = pref.edit();
                if (response.body() != null && response.body().getStatus() == 200) {
                    listData = response.body().getData();
                    if (listData != null && listData.size() > 0) {
                        Gson gson = new Gson();
                        JsonElement jsonElement = gson.toJsonTree(
                                listData, new TypeToken<List<GetAllExploreImageList>>() {
                                }.getType());
                        editor.putString("EXPLORE_WELCOME_DATA", jsonElement.toString()).apply();
                        productAdapter = new ProductListAdapter(ProductWelcomeScreenActivity.this, listData);
                        gridView.setAdapter(productAdapter);
                    } else {
                        checkLocalExplorerFile();
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    startActivity(new Intent(getBaseContext(), LoginActivity.class));
                    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;
                        startActivity(new Intent(getBaseContext(), LoginActivity.class));
                        finish();
                    }
                } else {
                    checkLocalExplorerFile();
                }
            }

            @Override
            public void onFailure(Call<GetAllExploreModel> call, Throwable t) {
                progressBar.setVisibility(View.GONE);
                checkLocalExplorerFile();
            }
        });
    }
    private void checkLocalExplorerFile() {
        SharedPreferences pref = getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
        if (pref.getString("EXPLORE_WELCOME_DATA", null) != null) {
            Gson gson = new Gson();
            List<GetAllExploreImageList> data = gson.fromJson(
                    pref.getString("EXPLORE_WELCOME_DATA", null),
                    new TypeToken<List<GetAllExploreImageList>>() {
                    }.getType());
            listData=data;
            productAdapter = new ProductListAdapter(ProductWelcomeScreenActivity.this, data);
            gridView.setAdapter(productAdapter);

        } else {
            Toast.makeText(this, "No data found", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_close:
                openCloseAlertBox();
                break;
            case R.id.imgBroucher:
                startActivity(new Intent(this, HyperMEnquiryForm.class));
                break;
            case R.id.img_rating:
                startActivity(new Intent(this, ProductFeedbackFormActivity.class));
                break;
            default:
        }
    }
    private void openCloseAlertBox() {
        final Dialog aDialog = new Dialog(this);
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_alert_close);
        aDialog.setCancelable(true);
        TextView aAlertMessage = aDialog.findViewById(R.id.txt_alert_message);
        aAlertMessage.setText("Dear " + storePreference.getStringValue(GlobalData.PRODUCT_NAME));
        aDialog.show();
        Button btnYes = aDialog.findViewById(R.id.btn_yes);
        Button btnNo = aDialog.findViewById(R.id.btn_no);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openFeedbackAlertBox();
                aDialog.dismiss();
            }
        });
        btnNo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                aDialog.dismiss();
            }

        });
    }
    private void openFeedbackAlertBox() {
        final Dialog aDialog = new Dialog(this);
        aDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        aDialog.setContentView(R.layout.popup_alert_feedback);
        aDialog.setCancelable(true);
        TextView aAlertMessage = aDialog.findViewById(R.id.txt_alert_message);
        aAlertMessage.setText("Dear " + storePreference.getStringValue(GlobalData.PRODUCT_NAME));
        aDialog.show();
        TextView txtSkip;
        ImageView imgClose;
        imgClose = aDialog.findViewById(R.id.img_close);
        txtSkip = aDialog.findViewById(R.id.txtSkip);
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aDialog.dismiss();
            }
        });
        txtSkip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                aDialog.dismiss();
                startActivity(new Intent(ProductWelcomeScreenActivity.this, ProductExploreDetailsActivity.class));
                finish();
            }
        });

        Button btnYes = aDialog.findViewById(R.id.btn_yes);
        btnYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ProductWelcomeScreenActivity.this, ProductFeedbackFormActivity.class));
                aDialog.dismiss();
            }
        });
    }
}