package it.integry.integrywmsnative.gest.pv_ordini_acquisto.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentActivity;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.R;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeCallbackDTO;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.data_store.db.entity.Griglia;
import it.integry.integrywmsnative.core.data_store.db.repository.GrigliaRepository;
import it.integry.integrywmsnative.core.expansion.BaseDialog;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.core.utility.UtilityProgress;
import it.integry.integrywmsnative.databinding.DialogScanCodiceGrigliaBinding;
import it.integry.integrywmsnative.gest.pv_ordini_acquisto.helper.OrdineAcquistoPvHelper;
import it.integry.integrywmsnative.view.dialogs.DialogProgressView;

public class DialogScanLisA {

    private FragmentActivity mContext;

    private BaseDialog mDialog;
    private DialogProgressView mCurrentProgress;

    private final DialogScanCodiceGrigliaBinding mBinding;

    private RunnableArgs<Griglia> mOnDialogDismiss;

    private OrdineAcquistoPvHelper mHelper;

    private GrigliaRepository mGrigliaRepository;
    private Griglia mGriglia;

    private DialogScanLisA(FragmentActivity context, GrigliaRepository grigliaRepository, OrdineAcquistoPvHelper helper, RunnableArgs<Griglia> onDialogDismiss) {
        mOnDialogDismiss = null;
        mContext = context;
        mGrigliaRepository = grigliaRepository;
        mHelper = helper;

        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mGriglia = null;
        mBinding = DataBindingUtil.inflate(inflater, R.layout.dialog_scan_codice_griglia, null, false);

        mDialog = new BaseDialog(context);
        mDialog.setContentView(mBinding.getRoot());
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mOnDialogDismiss = onDialogDismiss;
        initBarcode();

    }

    public static Dialog make(FragmentActivity context, GrigliaRepository grigliaRepository, OrdineAcquistoPvHelper helper, RunnableArgs<Griglia> onDialogDismiss) {
        return new DialogScanLisA(context, grigliaRepository, helper, onDialogDismiss).mDialog;
    }


    private void initBarcode() {

        int barcodeIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO()
                .setOnScanSuccessful(onScanSuccessfull)
                .setOnScanFailed(ex -> UtilityExceptions.defaultException(mContext, ex, false)));

        mDialog.setBarcodeListener(true);
        mDialog.setOnDismissListener(dialog -> {
            BarcodeManager.removeCallback(barcodeIstanceID);
            BarcodeManager.enable();
            mOnDialogDismiss.run(mGriglia);
        });
    }

    private final RunnableArgs<BarcodeScanDTO> onScanSuccessfull = data -> {
        BarcodeManager.disable();

        this.openProgress();
        Context context = mContext;
        RunnableArgs<Exception> mOnError = exception -> {
            mContext.runOnUiThread(() -> {
                this.closeProgress();
                UtilityExceptions.defaultException(context, exception);
                BarcodeManager.enable();
            });
        };

        RunnableArgs<Griglia> onGrigliaAvailable = griglia -> {
            mContext.runOnUiThread(() -> {
                this.closeProgress();
                mGriglia = griglia;
                mDialog.dismiss();
            });
        };


        mGrigliaRepository.findByCodAlis(data.getStringValue(), griglia -> {
            if (griglia != null) {
                griglia.getGriglia().setCountArticoli(griglia.getCountArticoli());
                mHelper.updateGriglia(griglia.getGriglia(), onGrigliaAvailable, mOnError);
            } else {
                mHelper.downloadAndSaveLisA(data.getStringValue(), onGrigliaAvailable, mOnError);
            }
        }, mOnError);


    };

    protected void openProgress() {
        mContext.runOnUiThread(() -> {
            if (this.mCurrentProgress == null) {
                this.mCurrentProgress = UtilityProgress.createDefaultProgressDialog(mContext);
            }
        });
    }

    protected void closeProgress() {
        mContext.runOnUiThread(() -> {
            if (mCurrentProgress != null) {
                mCurrentProgress.dismiss();
                mCurrentProgress = null;
            }
        });
    }
}
