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 android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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.ReportDamageStockHistory;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
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 DamagedStockHistory extends AppCompatActivity {
    public ArrayList<ReportDamageStockHistory> reportsList = new ArrayList<>();
    String counter_Id, visit_date, username;
    private SharedPreferences preferences;
    RecyclerView recycle_reports;
    ProgressDialog loading;
    Lorealba_Database db;
    Context context;

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

    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);
        setTitle("Reports Damaged Stock - " + visit_date);
        db = new Lorealba_Database(context);
        db.open();

        validatefilterui();
        call_adapter(context);
        if (CommonFunctions.checkNetIsAvailable(context)) {
            download_report(context);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();
    }

    private void call_adapter(Context context) {
        db.open();
        reportsList = db.getdamagestockhistory(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<ReportDamageStockHistory> data;

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

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

            holder.d_verifydate.setText(current.getVerifyDate());
            holder.d_verifydate.setId(position);

            holder.dverify.setText(current.getVerify());
            holder.dverify.setId(position);

            holder.ddamgeQTY.setText("" + current.getDamageQty());
            holder.ddamgeQTY.setId(position);

            holder.dmrp.setText("" + current.getMrp());
            holder.dmrp.setId(position);

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

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

            holder.dproduct_code.setText(current.getProductCode());
            holder.dproduct_code.setId(position);
            holder.dvisit_date.setText(current.getVisitDate());
            holder.dvisit_date.setId(position);
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView d_verifydate, dverify, ddamgeQTY, dmrp, dean_code, dproduct_name, dproduct_code, dvisit_date;
            CardView sale_card;

            public MyViewHolder(View itemView) {
                super(itemView);
                d_verifydate = (TextView) itemView.findViewById(R.id.d_verifydate);
                dverify = (TextView) itemView.findViewById(R.id.dverify);
                ddamgeQTY = (TextView) itemView.findViewById(R.id.ddamgeQTY);
                dmrp = (TextView) itemView.findViewById(R.id.dmrp);
                dean_code = (TextView) itemView.findViewById(R.id.dean_code);
                dproduct_name = (TextView) itemView.findViewById(R.id.dproduct_name);
                dproduct_code = (TextView) itemView.findViewById(R.id.dproduct_code);
                dvisit_date = (TextView) itemView.findViewById(R.id.dvisit_date);
                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);
            DamagedStockHistory.this.finish();

        }


        return super.onOptionsItemSelected(item);
    }

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

    }


    private void download_report(final Context context) {
        try {
            String download_key = "Report_DamageStockHistory";
            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();
                                    }
                                    ResponseResult reportsaleDatewiseObject = new Gson().fromJson(data, ResponseResult.class);
                                    if (reportsaleDatewiseObject != null) {
                                        db.open();
                                        if (db.insertdamagestockhistory(reportsaleDatewiseObject)) {
                                            call_adapter(context);
                                        }
                                    }
                                } else {
                                    loading.dismiss();
                                    if (loading != null && loading.isShowing()) {
                                        loading.dismiss();
                                    }
                                    db.open();
                                    db.delete_table_data("Report_DamageStockHistory");
                                    ///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);
        }
    }

    @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) -> {
        }));
    }
}
