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

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;
import androidx.fragment.app.DialogFragment;

import java.math.BigDecimal;
import java.math.RoundingMode;

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.data_store.db.entity.ArticoloOrdine;
import it.integry.integrywmsnative.core.expansion.BaseDialogFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityBigDecimal;
import it.integry.integrywmsnative.core.utility.UtilityObservable;
import it.integry.integrywmsnative.databinding.DialogPvEditArticoloBinding;

public class DialogEditArticoloView extends BaseDialogFragment implements DialogEditArticoloViewModel.Listener {

    @Inject
    DialogEditArticoloViewModel mViewModel;

    private final ArticoloOrdine mArticolo;
    private final RunnableArgs<ArticoloOrdine> mOnComplete;
    private final Runnable mOnAbort;

    public ObservableField<BigDecimal> currentNumCnf = new ObservableField<>();
    public ObservableField<BigDecimal> currentQtaCnf = new ObservableField<>();
    public ObservableField<BigDecimal> currentQtaTot = new ObservableField<>();

    private DialogPvEditArticoloBinding mBindings;
    private boolean mEnableDataCallback = true;

    public static DialogEditArticoloView newInstance(ArticoloOrdine articolo, RunnableArgs<ArticoloOrdine> onComplete, Runnable onAbort) {
        return new DialogEditArticoloView(articolo, onComplete, onAbort);
    }

    private DialogEditArticoloView(ArticoloOrdine articolo, RunnableArgs<ArticoloOrdine> onComplete, Runnable onAbort) {
        super();

        this.mArticolo = articolo;
        this.mOnComplete = onComplete;
        this.mOnAbort = onAbort;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBindings = DataBindingUtil.inflate(inflater, R.layout.dialog_pv_edit_articolo, container, false);
        mBindings.setLifecycleOwner(this);

        MainApplication.appComponent
                .dialogEditArticoloComponent()
                .create()
                .inject(this);

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        mBindings.toolbar.setTitle("Inserimento articolo");
        mBindings.inputQtaOrd.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);


        this.mViewModel
                .setListener(this)
                .setCurrentArticolo(this.mArticolo)
                .setInitialQtaCnf(BigDecimal.valueOf(mArticolo.getQtaCnf()))
                .setInitialNumCnf(UtilityBigDecimal.divide(BigDecimal.valueOf(mArticolo.getQtaOrd()), BigDecimal.valueOf(mArticolo.getQtaCnf())).setScale(0, RoundingMode.CEILING))
                .setInitialQtaTot(BigDecimal.valueOf(mArticolo.getQtaOrd()));

        mBindings.setView(this);

        this.onDataChanged();

        this.initBindings();

        return mBindings.getRoot();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.AppTheme_NewMaterial_Dialog_FullscreenDialog);
    }

    @Override
    public void onStart() {
        super.onStart();

        this.mViewModel.setListener(this);
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        this.mOnAbort.run();
        super.onDismiss(dialog);
    }

    private void initBindings() {

        UtilityObservable.addPropertyChanged(this.currentNumCnf, (value) -> {
            if (this.mEnableDataCallback) {
                this.mViewModel.setNumCnf(value);
            }
        });

        UtilityObservable.addPropertyChanged(this.currentQtaCnf, (value) -> {
            if (this.mEnableDataCallback) {
                this.mViewModel.setQtaCnf(value);
            }
        });

        UtilityObservable.addPropertyChanged(this.currentQtaTot, (value) -> {
            if (this.mEnableDataCallback) {
                this.mViewModel.setQtaTot(value);
            }
        });


        mBindings.inputQtaOrd.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                mBindings.inputNumCnfText.requestFocus();
                return true;
            }
            return false;
        });

        mBindings.inputNumCnfText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                saveAndExit();
                return true;
            }
            return false;
        });
    }

    public ArticoloOrdine getArticolo() {
        return mArticolo;
    }

    @Override
    public void onDataChanged() {
        this.mEnableDataCallback = false;

        this.currentNumCnf.set(this.mViewModel.getNumCnf());
        this.currentQtaCnf.set(this.mViewModel.getQtaCnf());
        this.currentQtaTot.set(this.mViewModel.getQtaTot());

        this.mBindings.executePendingBindings();

        this.mEnableDataCallback = true;
    }


    public void saveAndExit() {
        this.onLoadingStarted();

        this.mViewModel.save(newArticolo -> {
            this.mOnComplete.run(newArticolo);
            this.onLoadingEnded();
            dismiss();
        });
    }
}
