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.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.MasterBAProfileGetterSetter;
import com.cpm.lorealbaautomation.reportGetterSetter.ReportInwardStockSummary;
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 ReportsInwordStock extends AppCompatActivity {
    public ArrayList<ReportInwardStockSummary> reportsList = new ArrayList<>();
    String counter_Id, visit_date, username, report_name = "";
    private SharedPreferences preferences;
    RecyclerView recycle_reports;
    ProgressDialog loading = null;
    Lorealba_Database db;
    Context context;

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

    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);
        report_name = getIntent().getStringExtra(CommonString.Brand);
        setTitle("Reports " + report_name + "- " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
        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.getinwordStockSummary(counter_Id);
        if (!reportsList.isEmpty()) {
            recycle_reports.setAdapter(new ReportsAdapter(context, reportsList));
            recycle_reports.setLayoutManager(new LinearLayoutManager(context));
        }
    }

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

        public ReportsAdapter(Context context, List<ReportInwardStockSummary> 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_inword_stock, parent, false);
            return new MyViewHolder(view);
        }

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

            holder.invoice_no_txt.setText(current.getInvoiceNo());
            holder.invoice_no_txt.setId(position);

            holder.invoice_date_txt.setText(current.getInvoiceDate());
            holder.invoice_date_txt.setId(position);

            holder.invoice_type_txt.setText(current.getInvoiceType());
            holder.invoice_type_txt.setId(position);

            holder.source_txt.setText(current.getSource());
            holder.source_txt.setId(position);

            holder.invoice_value_txt.setText(current.getInvoiceValue().toString());
            holder.invoice_value_txt.setId(position);

            holder.total_line_txt.setText(current.getTotalLine().toString());
            holder.total_line_txt.setId(position);

            holder.confrm_line_txt.setText(current.getConfirmLine().toString());
            holder.confrm_line_txt.setId(position);

            holder.pending_line_txt.setText(current.getPendingLine().toString());
            holder.pending_line_txt.setId(position);


        }

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

        static class MyViewHolder extends RecyclerView.ViewHolder {
            TextView invoice_no_txt, invoice_date_txt, invoice_type_txt, source_txt, invoice_value_txt, total_line_txt, confrm_line_txt, pending_line_txt;

            public MyViewHolder(View itemView) {
                super(itemView);
                invoice_no_txt = (TextView) itemView.findViewById(R.id.invoice_no_txt);
                invoice_date_txt = (TextView) itemView.findViewById(R.id.invoice_date_txt);
                invoice_type_txt = (TextView) itemView.findViewById(R.id.invoice_type_txt);
                source_txt = (TextView) itemView.findViewById(R.id.source_txt);
                invoice_value_txt = (TextView) itemView.findViewById(R.id.invoice_value_txt);
                total_line_txt = (TextView) itemView.findViewById(R.id.total_line_txt);
                confrm_line_txt = (TextView) itemView.findViewById(R.id.confrm_line_txt);
                pending_line_txt = (TextView) itemView.findViewById(R.id.pending_line_txt);
            }
        }
    }

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

    }

    private void download_report(final Context context) {
        try {
            String download_key = "Report_InwardStockSummary";
            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();
                                    }
                                    ///caling adapter
                                    call_adapter(context);
                                } else if (!data.contains("No Data")) {
                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                    MasterBAProfileGetterSetter reportInwordStockSummeryGetterSetter = new Gson().fromJson(data, MasterBAProfileGetterSetter.class);
                                    if (reportInwordStockSummeryGetterSetter != null) {
                                        db.open();
                                        db.insertreport_inword_stock_summery(reportInwordStockSummeryGetterSetter);
                                    }
                                    ///caling adapter
                                    call_adapter(context);
                                } else {
                                    loading.dismiss();
                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                    db.open();
                                    db.delete_table_data("Report_InwardStockSummary");
                                    ///caling adapter
                                    call_adapter(context);
                                }

                            } catch (Exception e) {
                                loading.dismiss();
                                if (loading != null && loading.isShowing()) {
                                    loading.dismiss();
                                }
                                ///caling adapter
                                call_adapter(context);
                            }
                        } else {
                            loading.dismiss();
                            if (loading != null && loading.isShowing()) {
                                loading.dismiss();
                            }
                            ///caling adapter
                            call_adapter(context);
                        }
                    }

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

            } catch (Exception e) {
                loading.dismiss();
                if (loading != null && loading.isShowing()) {
                    loading.dismiss();
                }
                ///caling adapter
                call_adapter(context);
            }

        } catch (JSONException e) {
            loading.dismiss();
            if (loading != null && loading.isShowing()) {
                loading.dismiss();
            }
            ///caling adapter
            call_adapter(context);
        }
    }

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