package it.integry.integrywmsnative.gest.pv_ordine_acquisto_edit.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;

import androidx.databinding.DataBindingUtil;

import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.data_store.db.entity.ArticoloOrdine;
import it.integry.integrywmsnative.core.expansion.BaseDialog;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityDialog;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.core.utility.UtilityFocus;
import it.integry.integrywmsnative.core.utility.UtilityProgress;
import it.integry.integrywmsnative.databinding.DialogPvEditArticoloBinding;
import it.integry.integrywmsnative.gest.pv_ordine_acquisto_edit.helper.PVEditOrderHelper;

public class EditArticoloDialog {

    private Activity mContext;

    private Dialog mDialog;

    private DialogPvEditArticoloBinding mBinding;

    private PVEditOrderHelper mHelper;

    private ArticoloOrdine mArticolo;
    private ArticoloOrdine mSavedArt;

    private boolean mLockedInput = false;


    public static Dialog make(Activity context, PVEditOrderHelper helper, ArticoloOrdine articolo, RunnableArgs<ArticoloOrdine> onDialogDismiss) {
        return new EditArticoloDialog(context, helper, articolo, onDialogDismiss).mDialog;
    }


    private EditArticoloDialog(Activity context, PVEditOrderHelper helper, ArticoloOrdine articolo, RunnableArgs<ArticoloOrdine> onDialogDismiss) {
        mContext = context;
        mArticolo = articolo;
        mHelper = helper;

        mSavedArt = null;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mBinding = DataBindingUtil.inflate(inflater, R.layout.dialog_pv_edit_articolo, null, false);
        mBinding.setViewmodel(this);

        mDialog = new BaseDialog(context);
        mDialog.setContentView(mBinding.getRoot());
        UtilityDialog.setTo90PercentWidth(mContext, mDialog);
        mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        int qtaCnf = (int) Math.ceil(mArticolo.getQtaOrd() / mArticolo.getQtaCnf());
        mBinding.qtaTot.setText(String.valueOf(mArticolo.getQtaOrd()));
        mBinding.qtaCnf.setText(String.valueOf(qtaCnf));
        mDialog.setOnShowListener(dialog -> {
            UtilityFocus.focusTextBox(mContext, mBinding.qtaTot);
        });

        mDialog.setOnDismissListener(dialog -> {
            onDialogDismiss.run(mSavedArt);
        });
        setListeners();
    }

    private void setListeners() {
        mBinding.qtaTot.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setQtaOrd(s.toString().length() > 0 ? Float.parseFloat(s.toString()) : 0);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mBinding.qtaCnf.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                setQtaCnf(s.toString().length() > 0 ? Integer.parseInt(s.toString()) : 0);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public void setQtaCnf(int qtaCnf) {
        if (mLockedInput) {
            mLockedInput = false;
        } else {
            mLockedInput = true;

            float qtaTot = qtaCnf * mArticolo.getQtaCnf();
            mBinding.qtaTot.setText(String.valueOf(qtaTot));
        }
    }

    public void setQtaOrd(float qtaOrd) {
        mArticolo.setQtaOrd(qtaOrd);
        if (mLockedInput) {
            mLockedInput = false;
        } else {
            mLockedInput = true;
            mBinding.qtaCnf.setText(String.valueOf((int) Math.ceil(qtaOrd / mArticolo.getQtaCnf())));
        }
    }

    public void saveAndExit() {
        final Dialog progress = UtilityProgress.createDefaultProgressDialog(mContext);
        try {
            float qtaOrd = Float.parseFloat(mBinding.qtaTot.getText().toString());
            if (qtaOrd <= 0) {
                throw new Exception("La quantità ordinata deve essere maggiore di 0");
            }
            mArticolo.setQtaOrd(qtaOrd);

        } catch (Exception e) {
            mContext.runOnUiThread(() -> UtilityExceptions.defaultException(mContext, e));
            progress.dismiss();
            return;
        }
        mHelper.saveArticoloToOrdine(mArticolo, () -> {
            mSavedArt = mArticolo;
            progress.dismiss();
            mDialog.dismiss();
        }, e -> mContext.runOnUiThread(() -> UtilityExceptions.defaultException(mContext, e)));
    }

    public ArticoloOrdine getArticolo() {
        return mArticolo;
    }

    public void cancel() {
        mArticolo = null;
        mDialog.dismiss();
    }

}
