package com.cygnusa.hyperm;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
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.ProductFeedbackListAdapter;
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.util.TransparentProgressDialog;
import com.cygnusa.hyperm.wrappers.AnswerResponse;
import com.cygnusa.hyperm.wrappers.CustomerFeedbackModel;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.FeedbackAnswerArrayModel;
import com.cygnusa.hyperm.wrappers.FeedbackDataList;
import com.cygnusa.hyperm.wrappers.ProductFeedback;
import com.cygnusa.hyperm.wrappers.ProductFeedbackResponse;
import com.cygnusa.hyperm.wrappers.SingleTon;
import com.tylersuehr.esr.EmptyStateRecyclerView;

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

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


public class ProductFeedbackFormActivity extends AppCompatActivity
        implements View.OnClickListener {
    ImageButton backButton;
    Button submitBtn;
    ImageView imgBroucher, img_close;
    EmptyStateRecyclerView rcv_feedback_form;
    ApiService restService;
    ProductFeedbackListAdapter adapter;
    ArrayList<ProductFeedback> FEEDBACK_QUESTIONS = new ArrayList<>();
    LinearLayoutManager linearLayoutManager;
    private TransparentProgressDialog progressDialog;
    StorePreference storePreference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_feedback_form);
        backButton = findViewById(R.id.backButton);
        backButton.setOnClickListener(this);
        imgBroucher = findViewById(R.id.imgBroucher);
        imgBroucher.setOnClickListener(this);
        submitBtn = findViewById(R.id.submitButton);
        submitBtn.setOnClickListener(this);
        img_close = findViewById(R.id.img_close);
        img_close.setOnClickListener(this);

        storePreference = new StorePreference(this);
        restService = ((MainApplication) getApplication()).getClient();
        rcv_feedback_form = findViewById(R.id.surveyListView);
        rcv_feedback_form.setHasFixedSize(true);
        rcv_feedback_form.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(getBaseContext());
        rcv_feedback_form.setLayoutManager(linearLayoutManager);
        if (CommonMethods.isNetworkAvailable(this)) {
            getAllFeedbackQuestions();
            getAllOfflineAnswerSendToServer();

        } else {
            getLocal();
        }
    }
    private void hideKeyboard(Activity activity) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) activity.getSystemService(
                        Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(
                activity.getCurrentFocus().getWindowToken(), 0);
    }

    private void getLocal() {
        SharedPreferences pref = Objects.requireNonNull(ProductFeedbackFormActivity.this).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
        if (pref.getString("FEEDBACK_QUESTIONS_" + storePreference.getStringValue(GlobalData.FEEDBACK_MODEL), null) != null) {
            Gson gson = new Gson();
            FEEDBACK_QUESTIONS = gson.fromJson(
                    pref.getString("FEEDBACK_QUESTIONS_" + storePreference.getStringValue(GlobalData.FEEDBACK_MODEL), null),
                    new TypeToken<ArrayList<ProductFeedback>>() {
                    }.getType());
            if (FEEDBACK_QUESTIONS != null) {
                adapter = new ProductFeedbackListAdapter(ProductFeedbackFormActivity.this, FEEDBACK_QUESTIONS);
                rcv_feedback_form.setAdapter(adapter);
            }
        } else {
            Toast.makeText(ProductFeedbackFormActivity.this, "No data found", Toast.LENGTH_SHORT).show();
        }
    }

    private void getAllFeedbackQuestions() {
        restService.getAllFeedbackData().enqueue(new Callback<ProductFeedbackResponse>() {
            @Override
            public void onResponse(Call<ProductFeedbackResponse> call, Response<ProductFeedbackResponse> response) {
                if (response.body() != null && response.body().getStatus() == 200) {
                    SharedPreferences pref = Objects.requireNonNull(ProductFeedbackFormActivity.this).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = pref.edit();
                    if (response.body().getData() != null && response.body().getTotal() > 0) {
                        FEEDBACK_QUESTIONS = response.body().getData();
                        Gson gson = new Gson();
                        JsonElement jsonElement = gson.toJsonTree(
                                FEEDBACK_QUESTIONS, new TypeToken<ArrayList<ProductFeedback>>() {
                                }.getType());
                        editor.putString("FEEDBACK_QUESTIONS_" + storePreference.getStringValue(GlobalData.FEEDBACK_MODEL),
                                jsonElement.toString()).apply();

                        adapter = new ProductFeedbackListAdapter(ProductFeedbackFormActivity.this, FEEDBACK_QUESTIONS);
                        rcv_feedback_form.setAdapter(adapter);
                    } else {
                        GlobalData.showToast(getBaseContext(), "No data found.", Toast.LENGTH_SHORT).show();
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    CommonMethods.showToast(ProductFeedbackFormActivity.this, response.body().getMessage()).show();
                } 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();
                }
            }

            @Override
            public void onFailure(Call<ProductFeedbackResponse> call, Throwable t) {
                GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
            }
        });
    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void onSubmitAnswer() {
        if (ProductFeedbackListAdapter.feedbackAnsArr != null && ProductFeedbackListAdapter.feedbackAnsArr.size() > 0) {

            progressDialog = new TransparentProgressDialog(ProductFeedbackFormActivity.this);
            progressDialog.show();

            restService.sendFeedBack(buildConfigData()).enqueue(new Callback<AnswerResponse>() {
                @Override
                public void onResponse(Call<AnswerResponse> call, Response<AnswerResponse> response) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (response.body() != null && response.body().getStatus() == 200) {
                        CommonMethods.showToast(ProductFeedbackFormActivity.this, getResources().getString(R.string.message)).show();
                        startActivity(new Intent(ProductFeedbackFormActivity.this, ProductExploreDetailsActivity.class));
                        finish();
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        CommonMethods.showToast(ProductFeedbackFormActivity.this, response.body().getMessage()).show();
                        GlobalData.canLogout = true;
                        startActivity(new Intent(getBaseContext(), LoginActivity.class));
                        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;
                            startActivity(new Intent(getBaseContext(), LoginActivity.class));
                            finish();
                        }
                    }
                }

                @Override
                public void onFailure(Call<AnswerResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Kindly give atleast one feedback!", Toast.LENGTH_SHORT).show();
        }

    }

    private CustomerFeedbackModel buildConfigData() {
        CustomerFeedbackModel customerFeedbackModel = new CustomerFeedbackModel();
        customerFeedbackModel.setSmpin(GlobalData.user.getData().getSmpin());
        customerFeedbackModel.setEmpCode(GlobalData.user.getData().getEmp_code());
        FeedbackDataList feedbackDataLists = new FeedbackDataList();
        List<FeedbackDataList> feedbackDataListList = new ArrayList<>();
        List<FeedbackAnswerArrayModel> feedbackDataList = ProductFeedbackListAdapter.feedbackAnsArr;
        FeedbackAnswerArrayModel answerArrayModel;
        List<FeedbackAnswerArrayModel> answerArrayModelList = new ArrayList<>();
        if (feedbackDataList.size() > 0) {
            for (int i = 0; i < feedbackDataList.size(); i++) {
                answerArrayModel = new FeedbackAnswerArrayModel();
                answerArrayModel.setQid(feedbackDataList.get(i).getQid());
                answerArrayModel.setSurveyRating(feedbackDataList.get(i).getSurveyRating());
                answerArrayModelList.add(answerArrayModel);
            }
        }
        feedbackDataLists.setUid(storePreference.getStringValue(GlobalData.CURRENTTIME));
        feedbackDataLists.setFeedbackAnsArr(answerArrayModelList);
        feedbackDataListList.add(feedbackDataLists);
        customerFeedbackModel.setCustomerData(feedbackDataListList);
        return customerFeedbackModel;
    }

    private void openAlertBox() {

        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) {
                startActivity(new Intent(ProductFeedbackFormActivity.this, ProductExploreDetailsActivity.class));
                finish();
                aDialog.dismiss();
            }
        });
        btnNo.setOnClickListener(new View.OnClickListener() {

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

        });

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backButton:
                onBackPressed();
                break;
            case R.id.imgBroucher:
                startActivity(new Intent(ProductFeedbackFormActivity.this, HyperMEnquiryForm.class));
                finish();
                break;
            case R.id.submitButton:
                if (CommonMethods.isNetworkAvailable(this)) {
                    getAllOfflineAnswerSendToServer();
                    onSubmitAnswer();
                } else {
                    onSubmitLocalAnswer();
                }
                break;
            case R.id.img_close:
                openAlertBox();
                break;
            default:
        }
    }

    private void getAllOfflineAnswerSendToServer() {
        CustomerFeedbackModel customerFeedbackModel = new CustomerFeedbackModel();
        if (SingleTon.getInstance().feedbackModel.getCustomerData() != null && SingleTon.getInstance().feedbackModel.getCustomerData().size() > 0) {
            customerFeedbackModel = SingleTon.getInstance().feedbackModel;
        }
        if (customerFeedbackModel.getCustomerData() != null && customerFeedbackModel.getCustomerData().size() > 0) {
            restService.sendFeedBack(customerFeedbackModel).enqueue(new Callback<AnswerResponse>() {
                @Override
                public void onResponse(Call<AnswerResponse> call, Response<AnswerResponse> response) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (response.body() != null && response.body().getStatus() == 200) {
                        SingleTon.getInstance().feedbackModel = new CustomerFeedbackModel();
                        CommonMethods.showToast(ProductFeedbackFormActivity.this, response.body().getMessage()).show();
                        startActivity(new Intent(ProductFeedbackFormActivity.this, ProductExplorerActivity.class));
                        finish();
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        CommonMethods.showToast(ProductFeedbackFormActivity.this, response.body().getMessage()).show();
                    } 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();
                    }
                }

                @Override
                public void onFailure(Call<AnswerResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

    private void onSubmitLocalAnswer() {
        CustomerFeedbackModel customerFeedbackModel = new CustomerFeedbackModel();
        customerFeedbackModel.setSmpin(GlobalData.user.getData().getSmpin());
        customerFeedbackModel.setEmpCode(GlobalData.user.getData().getEmp_code());
        FeedbackDataList feedbackDataLists = new FeedbackDataList();
        List<FeedbackAnswerArrayModel> feedbackDataList = ProductFeedbackListAdapter.feedbackAnsArr;
        FeedbackAnswerArrayModel answerArrayModel;
        List<FeedbackAnswerArrayModel> answerArrayModelList = new ArrayList<>();
        if (feedbackDataList.size() > 0) {
            for (int i = 0; i < feedbackDataList.size(); i++) {
                answerArrayModel = new FeedbackAnswerArrayModel();
                answerArrayModel.setQid(feedbackDataList.get(i).getQid());
                answerArrayModel.setSurveyRating(feedbackDataList.get(i).getSurveyRating());
                answerArrayModelList.add(answerArrayModel);
            }
        }
        feedbackDataLists.setUid(storePreference.getStringValue(GlobalData.CURRENTTIME));
        feedbackDataLists.setFeedbackAnsArr(answerArrayModelList);
        SingleTon.getInstance().feedbackDataLists.add(feedbackDataLists);
        customerFeedbackModel.setCustomerData(SingleTon.getInstance().feedbackDataLists);
        SingleTon.getInstance().feedbackModel = customerFeedbackModel;
        startActivity(new Intent(ProductFeedbackFormActivity.this, ProductExplorerActivity.class));
        finish();
    }
}
