package com.cpm.lorealbaautomation.reports;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.getFilters;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;

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

import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterProfileQuestionGetterSetter;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportTop10Value;
import com.cpm.lorealbaautomation.retrofit.PostApi;

import org.json.JSONException;
import org.json.JSONObject;

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

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ReportsTop10Value extends AppCompatActivity {
    public ArrayList<ReportTop10Value> reportsList = new ArrayList<>();
    TextView str_mtd_valume, str_avgperday_calume;
    String counter_Id, visit_date, username, report_name = "";
    private SharedPreferences preferences;
    private ProgressDialog loading = null;
    RecyclerView recycle_reports;
    Lorealba_Database db;
    Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reports_name_list);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        iduserinterface();

        String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code);
        txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id);

    }


    private void iduserinterface() {
       preferences = PrefHelper.getPrefs(context);
        counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports);

        str_mtd_valume = (TextView) findViewById(R.id.str_mtd_valume);
        str_avgperday_calume = (TextView) findViewById(R.id.str_avgperday_calume);
        report_name = getIntent().getStringExtra(CommonString.Brand);
        setTitle("Reports " + report_name + "- " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
        validatefilterui();
        if (report_name.equals("Top 10 Value")) {
            str_mtd_valume.setText(getString(R.string.mtd_value));
            str_avgperday_calume.setText(getString(R.string.avg_perday_value));
            if (CommonFunctions.checkNetIsAvailable(context)) {
                download_report(context, true);
            } else {
                calculatedatafor_tp10Value("0");
            }
        } else {
            str_mtd_valume.setText(getString(R.string.mtd_valuume));
            str_avgperday_calume.setText(getString(R.string.avg_perday_volume));
            if (CommonFunctions.checkNetIsAvailable(context)) {
                download_report(context, false);
            } else {
                calculatedatafor_tp10Value("1");
            }
        }
    }


    private void calculatedatafor_tp10Value(String value) {
        if (value != null && value.equals("0")) {
            db.open();
            reportsList = db.gettop10Value(counter_Id);
        } else if (value != null && value.equals("1")) {
            db.open();
            reportsList = db.gettop10Valume(counter_Id);
        }

        if (!reportsList.isEmpty()) {
            recycle_reports.setAdapter(new ReportsAdapter(context, reportsList, value));
            recycle_reports.setLayoutManager(new LinearLayoutManager(context));
        }

    }


    private class ReportsAdapter extends RecyclerView.Adapter<ReportsAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ReportTop10Value> data;
        String value;

        public ReportsAdapter(Context context, List<ReportTop10Value> data, String value) {
            inflator = LayoutInflater.from(context);
            this.data = data;
            this.value = value;
        }

        @NonNull
        @Override
        public ReportsAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.row_reports_list, parent, false);
            return new ReportsAdapter.MyViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) {
            final ReportTop10Value current = data.get(position);

            holder.brand_name_txt.setText(current.getBrandName());
            holder.brand_name_txt.setId(position);

            holder.ean_code.setText(current.getEanCode());
            holder.ean_code.setId(position);

            holder.product_name.setText(current.getProductName());
            holder.product_name.setId(position);

            if (value.equals("0")) {
                holder.mtd_valume.setText(current.getMTDValue().toString());
                holder.mtd_valume.setId(position);
                holder.avgperday_calume.setText(current.getAvgPerDayValue().toString());
                holder.avgperday_calume.setId(position);
            } else {
                holder.mtd_valume.setText(current.getMTDValue().toString());
                holder.mtd_valume.setId(position);
                holder.avgperday_calume.setText(current.getAvgPerDayValue().toString());
                holder.avgperday_calume.setId(position);
            }

        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView brand_name_txt, ean_code, product_name, mtd_valume, avgperday_calume;
            CardView sale_card;

            public MyViewHolder(View itemView) {
                super(itemView);
                brand_name_txt = (TextView) itemView.findViewById(R.id.brand_name_txt);
                ean_code = (TextView) itemView.findViewById(R.id.promo_ean_code);
                product_name = (TextView) itemView.findViewById(R.id.product_name);
                mtd_valume = (TextView) itemView.findViewById(R.id.mtd_valume);
                avgperday_calume = (TextView) itemView.findViewById(R.id.avgperday_calume);
                sale_card = (CardView) itemView.findViewById(R.id.sale_card);
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ReportsTop10Value.this.finish();

        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        ReportsTop10Value.this.finish();

    }


    private void download_report(final Context context, final boolean flagfor_top10_value) {
        try {
            String download_key = "Report_Top10Volume";
            if (flagfor_top10_value) {
                download_key = "Report_Top10Value";
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", download_key);
            jsonObject.put("Username", username);
            jsonObject.put("Param1", counter_Id);
            jsonObject.put("Param2", "");
            String jsonString = jsonObject.toString();
            try {

                loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true);
                OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                        TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
                RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
                Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                PostApi api = adapter.create(PostApi.class);
                Call<ResponseBody> call = api.getTabjournePlan(jsonData);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                        ResponseBody responseBody = response.body();
                        String data = null;
                        if (responseBody != null && response.isSuccessful()) {
                            try {
                                loading.dismiss();
                                assert response.body() != null;
                                data = response.body().string();
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                    if (flagfor_top10_value) {
                                        calculatedatafor_tp10Value("0");
                                    } else {
                                        calculatedatafor_tp10Value("1");
                                    }
                                } else if (!data.contains("No Data")) {
                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                    if (flagfor_top10_value) {
                                        MasterProfileQuestionGetterSetter reportTop10ValueObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                        if (reportTop10ValueObject != null) {
                                            db.open();
                                            db.insertReportTop10Value(reportTop10ValueObject);
                                        }

                                    } else {
                                        MasterProfileQuestionGetterSetter reportTop10VolumeObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                        if (reportTop10VolumeObject != null) {
                                            db.open();
                                            db.insertReportTop10Volume(reportTop10VolumeObject);
                                        }
                                    }
                                    ///caling adapter
                                    if (flagfor_top10_value) {
                                        calculatedatafor_tp10Value("0");
                                    } else {
                                        calculatedatafor_tp10Value("1");
                                    }
                                } else {
                                    loading.dismiss();
                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                    if (flagfor_top10_value) {
                                        db.open();
                                        db.delete_table_data("Report_Top10Value");
                                    } else {
                                        db.open();
                                        db.delete_table_data("Report_Top10Volume");
                                    }

                                    ///caling adapter
                                    if (flagfor_top10_value) {
                                        calculatedatafor_tp10Value("0");
                                    } else {
                                        calculatedatafor_tp10Value("1");
                                    }
                                }
                            } catch (Exception e) {
                                loading.dismiss();
                                if (loading != null && loading.isShowing()) {
                                    loading.dismiss();
                                }
                                ///caling adapter
                                if (flagfor_top10_value) {
                                    calculatedatafor_tp10Value("0");
                                } else {
                                    calculatedatafor_tp10Value("1");
                                }
                            }
                        } else {
                            loading.dismiss();
                            if (loading != null && loading.isShowing()) {
                                loading.dismiss();
                            }
                            ///caling adapter
                            if (flagfor_top10_value) {
                                calculatedatafor_tp10Value("0");
                            } else {
                                calculatedatafor_tp10Value("1");
                            }
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        loading.dismiss();
                        if (loading != null && loading.isShowing()) {
                            loading.dismiss();
                        }
                        ///caling adapter
                        if (flagfor_top10_value) {
                            calculatedatafor_tp10Value("0");
                        } else {
                            calculatedatafor_tp10Value("1");
                        }
                    }
                });

            } catch (Exception e) {
                loading.dismiss();
                if (loading != null && loading.isShowing()) {
                    loading.dismiss();
                }
                ///caling adapter
                if (flagfor_top10_value) {
                    calculatedatafor_tp10Value("0");
                } else {
                    calculatedatafor_tp10Value("1");
                }

            }

        } catch (JSONException e) {
            loading.dismiss();
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
            }
            ///caling adapter
            if (flagfor_top10_value) {
                calculatedatafor_tp10Value("0");
            } else {
                calculatedatafor_tp10Value("1");
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (loading != null && loading.isShowing()) {
            loading.dismiss();
        }
        super.onDestroy();
    }

    @SuppressLint("NotifyDataSetChanged")
    private void validatefilterui() {
        RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3));
        rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), "Axe", true, false, (filterText, placeHolder) ->{} ));
    }
}
