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 android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.swipe.OnSwipeItemSelectedListener;
import com.cygnusa.hyperm.swipe.SwipeItem;
import com.cygnusa.hyperm.swipe.SwipeSelector;
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.List;
import java.util.Objects;

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

public class ProductExplorerActivity extends AppCompatActivity implements View.OnClickListener, OnSwipeItemSelectedListener {

    Button btnNext;
    SwipeSelector swipeSelector;
    StorePreference storePreference;
    String selectedModel = "1";
    GetAllExploreModel getAllExploreModel;
    ApiService restService;
    ProgressBar progressBar;
    ImageView img_home, img_close, img_broucher, img_rating;
    ImageView layout1;
    private TextView txtModelName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        restService = ((MainApplication) getApplication()).getClient();
        initViews();
        if (GlobalData.user.getData() != null)
            if (GlobalData.user.getData().getRole().equalsIgnoreCase("16")) {
                img_home.setVisibility(View.VISIBLE);
                layout1.setVisibility(View.GONE);
                img_rating.setVisibility(View.VISIBLE);
                img_broucher.setVisibility(View.VISIBLE);
                img_close.setVisibility(View.VISIBLE);
            } else {
                img_home.setVisibility(View.VISIBLE);
                layout1.setVisibility(View.VISIBLE);
                img_rating.setVisibility(View.GONE);
                img_broucher.setVisibility(View.GONE);
                img_close.setVisibility(View.GONE);
            }
    }

    @Override
    public void onBackPressed() {
        if (GlobalData.user.getData().getRole().equalsIgnoreCase("16")) {
            startActivity(new Intent(ProductExplorerActivity.this, ProductWelcomeScreenActivity.class));
            finish();
        } else {
            super.onBackPressed();
        }
    }

    private void initViews() {
        btnNext = findViewById(R.id.btnNext);
        btnNext.setOnClickListener(this);
        storePreference = new StorePreference(this);
        txtModelName = findViewById(R.id.txtModelName);
        progressBar = findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        getAllExploreModel = new GetAllExploreModel();
        swipeSelector = findViewById(R.id.swipeSelector);
        swipeSelector.setOnItemSelectedListener(this);
        img_home = findViewById(R.id.img_home);
        img_home.setOnClickListener(this);
        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);
        layout1 = findViewById(R.id.fabEnquiry);
        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ProductExplorerActivity.this, HyperMEnquiryForm.class));
            }
        });
        if (CommonMethods.isNetworkAvailable(this)) {
            getAllExploreImageDataList();
        } else {
            checkLocalExplorerFile();
        }
    }

    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) {
                    List<GetAllExploreImageList> data = response.body().getData();
                    if (data != null && data.size() > 0) {
                        Gson gson = new Gson();
                        JsonElement jsonElement = gson.toJsonTree(
                                data, new TypeToken<List<GetAllExploreImageList>>() {
                                }.getType());
                        editor.putString("EXPLORE_DATA", jsonElement.toString()).apply();

                        storePreference.setString(GlobalData.SELECTED_MODEL, data.get(0).getModelId());
                        storePreference.setString(GlobalData.SELECTED_MODEL_NAME, data.get(0).getModelName());
                        txtModelName.setText(data.get(0).getModelName());

                        SwipeItem[] swipeItems = new SwipeItem[data.size()];
                        for (int i = 0; i < data.size(); i++) {

                            SwipeItem item = new SwipeItem(data.get(i).getModelName(), data.get(i).getModelImageUrl(), data.get(i).getModelId());
                            swipeItems[i] = item;
                        }
                        swipeSelector.setItems(swipeItems);
                    } 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_DATA", null) != null) {
            Gson gson = new Gson();
            List<GetAllExploreImageList> data = gson.fromJson(
                    pref.getString("EXPLORE_DATA", null),
                    new TypeToken<List<GetAllExploreImageList>>() {
                    }.getType());
            SwipeItem[] swipeItems = new SwipeItem[Objects.requireNonNull(data).size()];
            for (int i = 0; i < data.size(); i++) {
                storePreference.setString(GlobalData.SELECTED_MODEL, data.get(0).getModelId());
                storePreference.setString(GlobalData.SELECTED_MODEL_NAME, data.get(0).getModelName());
                txtModelName.setText(data.get(0).getModelName());
                SwipeItem item = new SwipeItem(data.get(i).getModelName(), data.get(i).getModelImageUrl(), data.get(i).getModelId());
                swipeItems[i] = item;
            }
            swipeSelector.setItems(swipeItems);
        } else {
            Toast.makeText(this, "No data found", Toast.LENGTH_SHORT).show();
        }
    }

    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(ProductExplorerActivity.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(ProductExplorerActivity.this, ProductFeedbackFormActivity.class));
                aDialog.dismiss();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnNext:
                startActivity(new Intent(this, MainActivity.class));
                break;
            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;
            case R.id.img_home:
                if (GlobalData.user.getData().getRole().equalsIgnoreCase("16")) {
                    startActivity(new Intent(ProductExplorerActivity.this, ProductWelcomeScreenActivity.class));
                } else {
                    onBackPressed();
                }
                break;
            default:
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void onItemSelected(SwipeItem item) {
        int modelId = Integer.parseInt(item.getDescription());
        storePreference.setString(GlobalData.SELECTED_MODEL, item.getDescription());
        txtModelName.setText(item.getValue());
        storePreference.setString(GlobalData.SELECTED_MODEL_NAME, item.getValue());
    }
}
