package com.cpm.lorealbaMabeline.reports;

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

import android.annotation.SuppressLint;
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.LinearLayout;
import android.widget.TextView;

import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.adapter.SubAxeValueAdapter;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.gsonGetterSetter.TStockSummary;

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

public class TesterReportActivity extends AppCompatActivity {
    ArrayList<TStockSummary> reportsList = new ArrayList<>();
    String counter_Id, visit_date, username, report_name = "", default_type = "Axe";
    TextView brand_name, testername_txt, unit_of_testertxt;
    SharedPreferences preferences;
    RecyclerView recycle_reports;
    Lorealba_Database db;
    Context context;
    LinearLayout card_total_salestock, rlTester, rlOthers;
    TextView total_sales_qty, sale_value_total, tvTesterName, tvUnit_of_tester;

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


    @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, "");
        recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports);
        brand_name = (TextView) findViewById(R.id.brand_name);
        testername_txt = (TextView) findViewById(R.id.testername_txt);
        unit_of_testertxt = (TextView) findViewById(R.id.unit_of_testertxt);
        card_total_salestock = (LinearLayout) findViewById(R.id.card_total_salestock);
        rlTester = (LinearLayout) findViewById(R.id.rlTester);
        rlOthers = (LinearLayout) findViewById(R.id.rlOthers);
        total_sales_qty = (TextView) findViewById(R.id.total_sales_qty);
        sale_value_total = (TextView) findViewById(R.id.sale_value_total);
        tvTesterName = (TextView) findViewById(R.id.tvTesterName);
        tvUnit_of_tester = (TextView) findViewById(R.id.tvUnit_of_tester);
        report_name = getIntent().getStringExtra(CommonString.Brand);
        setTitle("Reports " + report_name + "- " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
        if (report_name.equalsIgnoreCase("Tester Stock Summary")) {
            tvTesterName.setText(default_type + " Name");
            tvUnit_of_tester.setText(getString(R.string.tester_availebility));
            reportsList = db.getreport_tester_stock(counter_Id, default_type + "Name");
            total_stock_calculate(true, reportsList);
            rlTester.setVisibility(View.VISIBLE);
            rlOthers.setVisibility(View.GONE);
        } else if (report_name.equalsIgnoreCase("Counter Coverage")) {
            db.open();
            brand_name.setText(getString(R.string.visitdate));
            testername_txt.setText(getString(R.string.counter_name));
            unit_of_testertxt.setText(getString(R.string.counter_code));
            reportsList = db.getStockCheckReport(visit_date, counter_Id, true, default_type + "Name");
            total_stock_calculate(true, reportsList);
            rlTester.setVisibility(View.GONE);
            rlOthers.setVisibility(View.VISIBLE);
        } else {
            db.open();
            rlTester.setVisibility(View.GONE);
            rlOthers.setVisibility(View.VISIBLE);
            brand_name.setText(default_type + " Name");
            setTitle(report_name + " - " + visit_date);
            testername_txt.setText(getString(R.string.stock_qty));
            unit_of_testertxt.setText(getString(R.string.stock_value));
            reportsList = db.getStockCheckReport(visit_date, counter_Id, false, default_type + "Name");
            total_stock_calculate(false, reportsList);
        }

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

    @SuppressLint("SetTextI18n")
    private void total_stock_calculate(boolean flag_tester, ArrayList<TStockSummary> reportsList) {
        try {
            if (flag_tester) {
                db.open();
                TStockSummary testStocksummery = db.gettesterstock(counter_Id);
                if (!reportsList.isEmpty() && testStocksummery != null) {
                    card_total_salestock.setVisibility(View.VISIBLE);
                    total_sales_qty.setText("");
                    sale_value_total.setText("Total " + getString(R.string.tester_availebility) + "\n" + testStocksummery.getTesterBalance());
                } else {
                    card_total_salestock.setVisibility(View.GONE);
                    total_sales_qty.setText("");
                    sale_value_total.setText("");
                }
            } else {
                db.open();
                TStockSummary stockSummary = db.getStockCheckTotalStockWithQty(visit_date, counter_Id);
                if (!reportsList.isEmpty() && stockSummary != null) {
                    card_total_salestock.setVisibility(View.VISIBLE);
                    total_sales_qty.setText("Total Stock QTY \n" + stockSummary.getStock());
                    sale_value_total.setText("Total Stock Value \n" + stockSummary.getMrp());
                } else {
                    card_total_salestock.setVisibility(View.GONE);
                    total_sales_qty.setText("");
                    sale_value_total.setText("");
                }
            }

        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

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

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

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final ReportsAdapter.MyViewHolder holder, final int position) {
            final TStockSummary current = data.get(position);
            if (report_name.equalsIgnoreCase("Tester Stock Summary")) {
                holder.itemRLTester.setVisibility(View.VISIBLE);
                holder.itemRLTester.setId(position);
                holder.itemRLOther.setVisibility(View.GONE);
                holder.itemRLOther.setId(position);

                holder.tvTesterName.setText(current.getProductName());
                holder.tvTesterName.setId(position);
                holder.tvTesterBalances.setText(current.getTesterBalance().toString());
                holder.tvTesterBalances.setId(position);
            } else if (report_name.equalsIgnoreCase("Counter Coverage")) {
                holder.itemRLTester.setVisibility(View.GONE);
                holder.itemRLTester.setId(position);
                holder.itemRLOther.setVisibility(View.VISIBLE);
                holder.itemRLOther.setId(position);

                holder.product_name.setText(current.getProductName());
                holder.product_name.setId(position);
                holder.tester_balance.setText(current.getGwpStatus());
                holder.tester_balance.setId(position);
                holder.brand_name_txt.setText(current.getBrand_name());
                holder.brand_name_txt.setId(position);
            } else {
                holder.itemRLTester.setVisibility(View.GONE);
                holder.itemRLTester.setId(position);
                holder.itemRLOther.setVisibility(View.VISIBLE);
                holder.itemRLOther.setId(position);
                holder.brand_name_txt.setText(current.getBrand_name());
                holder.brand_name_txt.setId(position);
                holder.product_name.setText(String.valueOf(current.getStock()));
                holder.product_name.setId(position);
                holder.tester_balance.setText(String.valueOf(current.getMrp()));
                holder.tester_balance.setId(position);
            }
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            LinearLayout itemRLOther, itemRLTester;
            TextView brand_name_txt, tester_balance, product_name,
                    tvTesterName, tvTesterBalances;

            public MyViewHolder(View itemView) {
                super(itemView);
                itemRLTester = (LinearLayout) itemView.findViewById(R.id.itemRLTester);
                itemRLOther = (LinearLayout) itemView.findViewById(R.id.itemRLOther);
                brand_name_txt = (TextView) itemView.findViewById(R.id.brand_name_txt);
                tester_balance = (TextView) itemView.findViewById(R.id.tester_balance);
                product_name = (TextView) itemView.findViewById(R.id.product_name);
                ////for tester
                tvTesterName = (TextView) itemView.findViewById(R.id.tvTesterName);
                tvTesterBalances = (TextView) itemView.findViewById(R.id.tvTesterBalances);
            }
        }
    }

    @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("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, report_name.equals("Counter Coverage"), false, this::callAdapter));
    }
    private void callAdapter(String column_name, String place_holder) {
        String compColumn = column_name.replaceAll(" ", "");
        compColumn += "Name";
        if (report_name.equalsIgnoreCase("Tester Stock Summary")) {
            tvTesterName.setText(place_holder);
            reportsList = db.getreport_tester_stock(counter_Id, compColumn);
        } else if (report_name.equalsIgnoreCase("Counter Coverage")) {
            brand_name.setText(getString(R.string.visitdate));
            reportsList = db.getStockCheckReport(visit_date, counter_Id, true, compColumn);
        } else {
            brand_name.setText(place_holder);
            reportsList = db.getStockCheckReport(visit_date, counter_Id, false, compColumn);
        }

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