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.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

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

import android.text.Html;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
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.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.BADeviceLoginGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesDateWise;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesL3MValue;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
import com.cpm.lorealbaautomation.retrofit.PostApi;

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

import java.io.Serializable;
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 ReportDayWiseActivity extends AppCompatActivity {
    ArrayList<ReportSalesDateWise> reportsList = new ArrayList<>();
    String counter_Id, visit_date, username, userType;
    SharedPreferences preferences;
    RecyclerView recycle_reports, threemonth_salesRecycle;
    ArrayList<ReportSalesL3MValue> salesL3MValues = new ArrayList<>();
    LinearLayout rl_threemonthsales;
    ProgressDialog loading;
    Lorealba_Database db;
    Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reports_daywise);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        userType = getIntent().getStringExtra(CommonString.KEY_USER_TYPE);
        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();
    }

    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);
        rl_threemonthsales = (LinearLayout) findViewById(R.id.rl_threemonthsales);
        threemonth_salesRecycle = (RecyclerView) findViewById(R.id.threemonth_salesRecycle);
        setTitle("Reports DayWise - " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
        salesL3MValues = db.getreportthreemonthsalevalue(userType);
        if (!salesL3MValues.isEmpty()) {
            rl_threemonthsales.setVisibility(View.VISIBLE);
            threemonth_salesRecycle.setAdapter(new SalesValueAdapter(context, salesL3MValues));
            threemonth_salesRecycle.setLayoutManager(new LinearLayoutManager(context));
        } else {
            rl_threemonthsales.setVisibility(View.GONE);
        }
        if (CommonFunctions.checkNetIsAvailable(context)) {
            download_report(context);
        } else {
            call_adapter(context);
        }
    }

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

    private void call_adapter(Context context) {
        db.open();
        reportsList = db.getreportdaywisesale(counter_Id, userType);
        if (!reportsList.isEmpty()) {
            recycle_reports.setAdapter(new ReportsAdapter(context, reportsList));
            recycle_reports.setLayoutManager(new LinearLayoutManager(context));
        }
    }

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

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

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

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final ReportsAdapter.MyViewHolder holder, final int position) {
            final ReportSalesDateWise current = data.get(position);
            holder.datewith_day.setText(Html.fromHtml(current.getVisitDate() + " - " + current.getWeekDays()));
            holder.datewith_day.setId(position);

            holder.txt_qty.setText(String.valueOf(current.getQty()));
            holder.txt_qty.setId(position);

            holder.txt_salevalue.setText(String.valueOf(current.getSalesValue()));
            holder.txt_salevalue.setId(position);

            holder.datewith_day.setOnClickListener(view -> {
                if (CommonFunctions.checkNetIsAvailable(context)) {
                    downloadreportConsumerWise(current);
                } else {
                    AlertandMessages.showToastMsg(context, getString(R.string.nonetwork) + ". For viewing consumer wise report");
                }
            });

        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView datewith_day, txt_qty, txt_salevalue;

            public MyViewHolder(View itemView) {
                super(itemView);
                datewith_day = (TextView) itemView.findViewById(R.id.datewith_day);
                txt_qty = (TextView) itemView.findViewById(R.id.txt_qty);
                txt_salevalue = (TextView) itemView.findViewById(R.id.txt_salevalue);
            }
        }
    }


    private static class SalesValueAdapter extends RecyclerView.Adapter<SalesValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        ArrayList<ReportSalesL3MValue> data;

        public SalesValueAdapter(Context context, ArrayList<ReportSalesL3MValue> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;
        }

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

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

            holder.sales_months.setText(current.getMonth());
            holder.sales_months.setId(position);

            holder.txt_qty.setText(String.valueOf(current.getQty()));
            holder.txt_qty.setId(position);

            holder.txt_salevalue.setText(String.valueOf(current.getSalesValue()));
            holder.txt_salevalue.setId(position);

        }

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

        private static class MyViewHolder extends RecyclerView.ViewHolder {
            TextView sales_months, txt_qty, txt_salevalue;

            public MyViewHolder(View itemView) {
                super(itemView);
                sales_months = (TextView) itemView.findViewById(R.id.sales_months);
                txt_qty = (TextView) itemView.findViewById(R.id.txt_qty);
                txt_salevalue = (TextView) itemView.findViewById(R.id.txt_salevalue);
            }
        }
    }

    @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);
            ReportDayWiseActivity.this.finish();
        }

        return super.onOptionsItemSelected(item);
    }

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

    }

    private void downloadreportConsumerWise(ReportSalesDateWise current) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_SalesConsumerWiseME" : "Report_SalesConsumerWise");
            obj.put("Username", username);
            obj.put("Param1", current.getCounterId());
            obj.put("Param2", current.getVisitDate());
            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"), obj.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<String> call_login_tym = api.getDownloadAll(jsonData);
            call_login_tym.enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data_consumer_wise = null;
                    if (responseBody != null && response.isSuccessful()) {
                        loading.dismiss();
                        if (loading != null && loading.isShowing()) {
                            loading.dismiss();
                        }
                        try {
                            data_consumer_wise = response.body();
                            assert data_consumer_wise != null;
                            if (!data_consumer_wise.isEmpty()) {
                                BADeviceLoginGetterSetter consumerwiseSaleObject = null;
                                if (!data_consumer_wise.contains("No Data")) {
                                    consumerwiseSaleObject = new Gson().fromJson(data_consumer_wise, BADeviceLoginGetterSetter.class);
                                    if (consumerwiseSaleObject != null) {
                                        startActivity(new Intent(context, ReportConsumerWiseActivity.class)
                                                .putExtra(CommonString.TAG_OBJECT,
                                                        userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ?
                                                                (Serializable) consumerwiseSaleObject.getReportSalesConsumerWiseMe() :
                                                                (Serializable) consumerwiseSaleObject
                                                                        .getReportSalesConsumerWise()).putExtra(CommonString.KEY_USER_TYPE, userType));
                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                    }
                                } else {
                                    AlertandMessages.showToastMsg(context, "Day Wise Sale Report Not found");
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString());
                            loading.dismiss();
                        }
                    } else {
                        loading.dismiss();
                        AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showToastMsg(context, CommonString.MESSAGE_SOCKETEXCEPTION);
                }
            });

        } catch (JSONException e) {
            e.fillInStackTrace();
            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_INVALID_JSON);
        }
    }


    private void download_report(final Context context) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_SalesConsumerWiseME" : "Report_SalesConsumerWise");
            jsonObject.put("Username", username);
            jsonObject.put("Param1", counter_Id);
            jsonObject.put("Param2", "");
            String jsonString = jsonObject.toString();

            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();
                                }

                                call_adapter(context);
                            } else if (!data.contains("No Data")) {
                                if (loading != null && loading.isShowing()) {
                                    loading.dismiss();
                                }

                                ResponseResult reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class);
                                if (reportsaleDatewiseObject != null) {
                                    db.open();
                                    db.insertReportDaywiseSale(reportsaleDatewiseObject, userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME));
                                }

                                call_adapter(context);


                            } else {
                                if (loading != null && loading.isShowing()) {
                                    loading.dismiss();
                                }
                                db.open();
                                db.delete_table_data(userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_SalesConsumerWiseME" : "Report_SalesConsumerWise");
                                call_adapter(context);
                            }
                        } catch (Exception e) {
                            if (loading != null && loading.isShowing()) {
                                loading.dismiss();
                            }
                            call_adapter(context);
                        }
                    } else {
                        if (loading != null && loading.isShowing()) {
                            loading.dismiss();
                        }

                        call_adapter(context);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                    if (loading != null && loading.isShowing()) {
                        loading.dismiss();
                    }
                    call_adapter(context);
                }
            });
        } catch (Exception e) {
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
            }
            call_adapter(context);
        }
    }

    @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(), "Sub Axe", true,false, (filterText, placeHolder) -> {}));
    }
}
