package com.cpm.lorealbaautomation.reports.countervaluevolume;

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 android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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.adapter.VolumeDetailAdapter;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.databinding.DetailTesterUsageBinding;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolume;
import com.cpm.lorealbaautomation.gsonGetterSetter.countervolune.ReportCounterVolumeDetail;
import com.cpm.lorealbaautomation.retrofit.PostApi;

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

import java.util.ArrayList;
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 CounterValueVolumeDetailActivity extends AppCompatActivity {
    TextView tvCounterValue, tvMTDVolumePlaceholder, AvgPerDayVolumePlaceholder, tvMTDVolume, AvgPerDayVolume,
            tvCounterVolumeDetail, tvParamCode, tvParamName, tvMTDVolumeDetail, tvAvgPerDayVolumeDetail;
    ArrayList<ReportCounterVolumeDetail> volumeDetails = new ArrayList<>();
    String counter_Id, visit_date, username, default_type = "Axe", reportName = "";
    LinearLayout rlCounterVolume, rlCounterVolumeDetails;
    RecyclerView recyclCounterVolumeDetail;
    private SharedPreferences preferences;
    boolean value_flag = false;
    Lorealba_Database db;
    Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter_value);
        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);
        validatefilterui();
    }

    @SuppressLint("SetTextI18n")
    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, "");

        tvCounterValue = (TextView) findViewById(R.id.tvCounterValue);
        tvMTDVolumePlaceholder = (TextView) findViewById(R.id.tvMTDVolumePlaceholder);
        AvgPerDayVolumePlaceholder = (TextView) findViewById(R.id.AvgPerDayVolumePlaceholder);
        tvMTDVolume = (TextView) findViewById(R.id.tvMTDVolume);
        AvgPerDayVolume = (TextView) findViewById(R.id.AvgPerDayVolume);
        //////details
        tvCounterVolumeDetail = (TextView) findViewById(R.id.tvCounterVolumeDetail);
        tvParamCode = (TextView) findViewById(R.id.tvParamCode);
        tvParamName = (TextView) findViewById(R.id.tvParamName);
        tvMTDVolumeDetail = (TextView) findViewById(R.id.tvMTDVolumeDetail);
        tvAvgPerDayVolumeDetail = (TextView) findViewById(R.id.tvAvgPerDayVolumeDetail);

        rlCounterVolume = (LinearLayout) findViewById(R.id.rlCounterVolume);
        recyclCounterVolumeDetail = (RecyclerView) findViewById(R.id.recyclCounterVolumeDetail);
        rlCounterVolumeDetails = (LinearLayout) findViewById(R.id.rlCounterVolumeDetails);
        if (getIntent().getStringExtra(CommonString.Brand) != null) {
            reportName = getIntent().getStringExtra(CommonString.Brand);
        }
        assert reportName != null;
        db.open();
        ReportCounterVolume counterVolume = db.getCounterVolume(counter_Id, false);
        if (reportName.equalsIgnoreCase("Counter Value Detail")) {
            db.open();
            value_flag = true;
            counterVolume = db.getCounterVolume(counter_Id, true);
            AvgPerDayVolumePlaceholder.setText("AvgPer Day Value");
            tvCounterValue.setText("Counter Top 10 Value");
            tvMTDVolumePlaceholder.setText("MTD Value");
            tvCounterVolumeDetail.setText("Counter Top 10 Value Details");
            tvAvgPerDayVolumeDetail.setText("AvgPer Day Value");
            tvMTDVolumeDetail.setText("MTD Value");
        }

        if (counterVolume != null) {
            tvMTDVolume.setText(counterVolume.getMTDVolume() != null ? counterVolume.getMTDVolume().toString() : "0");
            AvgPerDayVolume.setText(counterVolume.getAvgPerDayVolume() != null ? counterVolume.getAvgPerDayVolume().toString() : "0");
        }

        counterVolumeDetails(default_type, null);
        setTitle(reportName + " Report " + " - " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
    }

    @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);
            this.finish();
        }
        return super.onOptionsItemSelected(item);
    }

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

    @SuppressLint("SetTextI18n")
    private void counterVolumeDetails(String param, ProgressDialog dialog) {
        //details
        volumeDetails = db.getCounterVolumeDetails(counter_Id, value_flag);
        if (!volumeDetails.isEmpty()) {
            tvParamCode.setText(param + " Code");
            tvParamName.setText(param + " Name");
            recyclCounterVolumeDetail.setAdapter(new VolumeDetailAdapter(context, volumeDetails));
            recyclCounterVolumeDetail.setLayoutManager(new LinearLayoutManager(context));
            rlCounterVolumeDetails.setVisibility(View.VISIBLE);
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    @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(), default_type, false, true, (filterText, placeHolder) -> download_report(context, filterText)));
    }

    private void download_report(final Context context, String param) {
        ProgressDialog loading = null;
        try {
            String cParam = param;
            cParam = cParam.replaceAll(" ", "") + "Name";
            String download_key = value_flag ? "Report_ConterValueDetail" : "Report_CounterVolumeDetail";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", download_key);
            jsonObject.put("Username", username);
            jsonObject.put("Param1", counter_Id);
            jsonObject.put("Param2", cParam);
            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);
                ProgressDialog finalLoading = loading;
                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 {
                                finalLoading.dismiss();
                                assert response.body() != null;
                                data = response.body().string();
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.contains("No Data") || data.equalsIgnoreCase(CommonString.KEY_FAILURE) || data.contains("Failure;Cannot find table 0.")) {
                                    counterVolumeDetails(param, finalLoading);
                                } else {
                                    ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class);
                                    if (counterVolumeDetail != null) {
                                        if (value_flag) {
                                            db.open();
                                            db.insertCounterValueDetail(counterVolumeDetail);
                                        } else {
                                            db.open();
                                            db.insertCounterVolumeDetail(counterVolumeDetail);
                                        }

                                        counterVolumeDetails(param, finalLoading);
                                    }
                                }
                            } catch (Exception e) {
                                counterVolumeDetails(param, finalLoading);
                            }
                        } else {
                            counterVolumeDetails(param, finalLoading);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        counterVolumeDetails(param, finalLoading);
                    }
                });
            } catch (Exception e) {
                counterVolumeDetails(param, null);
            }
        } catch (JSONException e) {
            counterVolumeDetails(param, null);
        }
    }

}