package com.cpm.lorealbaMabeline.reports.inwarddetails;

import static com.cpm.lorealbaMabeline.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.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.adapter.InwardStkDetailAdapter;
import com.cpm.lorealbaMabeline.adapter.SubAxeValueAdapter;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.gsonGetterSetter.ResponseResult;
import com.cpm.lorealbaMabeline.gsonGetterSetter.inwordDetail.ReportCounterInwardStock;
import com.cpm.lorealbaMabeline.gsonGetterSetter.inwordDetail.ReportCounterInwardStockDetail;
import com.cpm.lorealbaMabeline.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 CounterInwordDetailActivity extends AppCompatActivity {
    TextView tvInvoiceQty, tvActualQty,
            tvDamageQty, tvMissingQTY, tvParamCode, tvParamName;
    TextView headerStk, tvPlaceInvoice, tvPlaceActual, tvPlaceDamage, tvPlaceMissing,
            headerStkDetail, tvPlaceInvoiceDetail, tvPlaceActualDetail, tvPlaceDamageDetail, tvPlaceMissingDetail;
    ArrayList<ReportCounterInwardStockDetail> inwardStockDetails = new ArrayList<>();
    String counter_Id, visit_date, username, default_type = "Axe", reportName = "";
    LinearLayout rlCounterInwordStk, rlCounterInwordStkDetails;
    RecyclerView recyclCounterInwordStkDetail;
    private SharedPreferences preferences;
    private boolean inward_detail = true;
    Lorealba_Database db;
    Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_counter_inword_detail);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        headerStk = findViewById(R.id.headerStk);
        tvPlaceInvoice = findViewById(R.id.tvPlaceInvoice);
        tvPlaceActual = findViewById(R.id.tvPlaceActual);
        tvPlaceDamage = findViewById(R.id.tvPlaceDamage);
        tvPlaceMissing = findViewById(R.id.tvPlaceMissing);
        ///Details place holder Ids
        headerStkDetail = findViewById(R.id.headerStkDetail);
        tvPlaceInvoiceDetail = findViewById(R.id.tvPlaceInvoiceDetail);
        tvPlaceActualDetail = findViewById(R.id.tvPlaceActualDetail);
        tvPlaceDamageDetail = findViewById(R.id.tvPlaceDamageDetail);
        tvPlaceMissingDetail = findViewById(R.id.tvPlaceMissingDetail);
        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, "");
        tvInvoiceQty = (TextView) findViewById(R.id.tvInvoiceQty);
        tvActualQty = (TextView) findViewById(R.id.tvActualQty);
        //////details
        tvDamageQty = (TextView) findViewById(R.id.tvDamageQty);
        tvMissingQTY = (TextView) findViewById(R.id.tvMissingQTY);
        tvParamCode = (TextView) findViewById(R.id.tvParamCode);
        tvParamName = (TextView) findViewById(R.id.tvParamName);

        rlCounterInwordStk = (LinearLayout) findViewById(R.id.rlCounterInwordStk);
        recyclCounterInwordStkDetail = (RecyclerView) findViewById(R.id.recyclCounterInwordStkDetail);
        rlCounterInwordStkDetails = (LinearLayout) findViewById(R.id.rlCounterInwordStkDetails);
        if (getIntent().getStringExtra(CommonString.Brand) != null) {
            reportName = getIntent().getStringExtra(CommonString.Brand);
        }
        assert reportName != null;
        if (reportName.equalsIgnoreCase("Stock Ledger Detail")) {
            inward_detail = false;
        }


        db.open();
        setPlaceholderText();
        ReportCounterInwardStock inwordStk = db.getCounterInwordStk(counter_Id, inward_detail);
        if (inwordStk != null) {
            tvInvoiceQty.setText(inwordStk.getInvoiceQty() != null ? inwordStk.getInvoiceQty().toString() : "0");
            tvActualQty.setText(inwordStk.getActualQty() != null ? inwordStk.getActualQty().toString() : "0");
            tvDamageQty.setText(inwordStk.getDamageQty() != null ? inwordStk.getDamageQty().toString() : "0");
            tvMissingQTY.setText(inwordStk.getMissedQty() != null ? inwordStk.getMissedQty().toString() : "0");
        }

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

    @SuppressLint("SetTextI18n")
    private void setPlaceholderText() {
        if (!inward_detail) {
            headerStk.setText("Counter Stock Ledger");
            tvPlaceInvoice.setText("Opening Stock");
            tvPlaceInvoiceDetail.setText("Opening Stock");
            tvPlaceActual.setText("Stock-In");
            tvPlaceActualDetail.setText("Stock-In");
            tvPlaceDamage.setText("Sale-Out");
            tvPlaceDamageDetail.setText("Sale-Out");
            tvPlaceMissing.setText("Saleable Balance");
            tvPlaceMissingDetail.setText("Saleable Balance");
            headerStkDetail.setText("Counter Stock Ledger Detail");

        }
    }

    @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 counterInwordStkDetails(String param, ProgressDialog dialog) {
        //details
        inwardStockDetails = db.getCounterInwordStkDetails(counter_Id, inward_detail);
        if (!inwardStockDetails.isEmpty()) {
            tvParamCode.setText(param + " Code");
            tvParamName.setText(param + " Name");
            recyclCounterInwordStkDetail.setAdapter(new InwardStkDetailAdapter(context, inwardStockDetails));
            recyclCounterInwordStkDetail.setLayoutManager(new LinearLayoutManager(context));
            rlCounterInwordStkDetails.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";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", inward_detail ? "Report_CounterInwardStockDetail" : "Report_CounterStockLedgerDetail");
            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.")) {
                                    counterInwordStkDetails(param, finalLoading);
                                } else {
                                    ResponseResult counterVolumeDetail = new Gson().fromJson(data, ResponseResult.class);
                                    if (counterVolumeDetail != null) {
                                        db.open();
                                        if (inward_detail) {
                                            db.insertCounterInwardStockDetail(counterVolumeDetail);
                                        } else {
                                            db.insertCounterStockLedgerDetail(counterVolumeDetail);
                                        }
                                        counterInwordStkDetails(param, finalLoading);
                                    }
                                }
                            } catch (Exception e) {
                                counterInwordStkDetails(param, finalLoading);
                            }
                        } else {
                            counterInwordStkDetails(param, finalLoading);
                        }
                    }

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

        } catch (JSONException e) {
            counterInwordStkDetails(param, null);
        }
    }

}