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

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;

import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.List;

import javax.inject.Inject;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.MainApplication;
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.view_model.ArticoloDTO;
import it.integry.integrywmsnative.core.exception.GridNotFoundException;
import it.integry.integrywmsnative.core.expansion.BaseDialogFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.expansion.RunnableArgss;
import it.integry.integrywmsnative.core.rest.consumers.PVOrdiniAcquistoRESTConsumer;
import it.integry.integrywmsnative.databinding.DialogScanCodiceGrigliaBinding;

public class DialogScanGrigliaAcquistoView extends BaseDialogFragment {

    private DialogScanCodiceGrigliaBinding mBinding;
    private int mBarcodeScannerIstanceID;

    private final RunnableArgss<Griglia, List<ArticoloDTO>> mOnDialogDismiss;

    @Inject
    PVOrdiniAcquistoRESTConsumer pvOrdiniAcquistoRESTConsumer;

    private Griglia mGriglia;
    private List<ArticoloDTO> mListArticoli;


    public static DialogScanGrigliaAcquistoView newInstance(RunnableArgss<Griglia, List<ArticoloDTO>> onDialogDismiss) {
        return new DialogScanGrigliaAcquistoView(onDialogDismiss);
    }

    private DialogScanGrigliaAcquistoView(RunnableArgss<Griglia, List<ArticoloDTO>> onDialogDismiss) {
        super();
        mOnDialogDismiss = onDialogDismiss;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        this.initBarcode();

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

        mBinding = DataBindingUtil.inflate(LayoutInflater.from(requireContext()), R.layout.dialog_scan_codice_griglia, null, false);
        mBinding.setLifecycleOwner(this);
        mBinding.setView(this);

        var alertDialogBuilder = new MaterialAlertDialogBuilder(requireContext())
                .setView(mBinding.getRoot())
                .setCancelable(true);

        var alertDialog = alertDialogBuilder.create();
        alertDialog.setCanceledOnTouchOutside(true);
        return alertDialog;
    }

    private void initBarcode() {
        mBarcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO()
                .setOnScanSuccessful(onScanSuccessfull)
                .setOnScanFailed(this::onError));

        this.setBarcodeListener(true);
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        BarcodeManager.removeCallback(mBarcodeScannerIstanceID);
        mOnDialogDismiss.run(mGriglia, mListArticoli);

        super.onDismiss(dialog);
    }

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

        RunnableArgs<Exception> mOnError = exception -> {
            this.onError(exception);
            BarcodeManager.enable();
        };

        fetchArticoli(data.getStringValue(), mOnError);
    };

    public void fetchArticoli(String codAlis, RunnableArgs<Exception> onFailed) {
        this.onLoadingStarted();
        pvOrdiniAcquistoRESTConsumer.getArticoliListino(codAlis, dto -> {
            this.onLoadingEnded();
            if (dto.getGrigliaAcquistiChild().size() <= 0) {
                onFailed.run(new GridNotFoundException(codAlis));
                return;
            }

            mGriglia = new Griglia();
            mGriglia.setCodAlis(codAlis);
            mGriglia.setDescrLisa(dto.getDescrLisa());
            mGriglia.setDescrDepo(dto.getDescrDepo());
            mListArticoli = dto.getGrigliaAcquistiChild();
            this.dismiss();
        }, onFailed);
    }

}
