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

import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeCallbackDTO;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.expansion.BaseDialogFragment;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.utility.UtilityBarcode;
import it.integry.integrywmsnative.databinding.DialogStartProductionBinding;

public class DialogRecoverUl extends BaseDialogFragment {
    private int barcodeScannerIstanceID = -1;
    private RunnableArgs<BarcodeScanDTO> onScanSuccessful;
    private DialogStartProductionBinding mBinding;

    public static DialogRecoverUl newInstance(RunnableArgs<BarcodeScanDTO> onScanSuccessful) {

        Bundle args = new Bundle();

        DialogRecoverUl fragment = new DialogRecoverUl();
        fragment.setArguments(args);
        fragment.setOnScanSuccessful(onScanSuccessful);
        return fragment;
    }


    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        BarcodeManager.removeCallback(barcodeScannerIstanceID);
        super.onDismiss(dialog);
    }

    public DialogRecoverUl setOnScanSuccessful(RunnableArgs<BarcodeScanDTO> onScanSuccessful) {
        this.onScanSuccessful = onScanSuccessful;
        return this;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DialogStartProductionBinding.inflate(inflater, container, false);
        mBinding.setLifecycleOwner(this);
        this.initBarcodeReader();
        setCancelable(true);
        getDialog().setCanceledOnTouchOutside(true);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        return mBinding.getRoot();
    }


    private void initBarcodeReader() {
        barcodeScannerIstanceID = BarcodeManager.addCallback(new BarcodeCallbackDTO()
                .setOnScanSuccessful(this::processBarcode)
                .setOnScanFailed(this::onError));
        BarcodeManager.enable();
    }

    private void processBarcode(BarcodeScanDTO barcodeScanDTO) {
        if (UtilityBarcode.isEan128(barcodeScanDTO)) {
            this.onScanSuccessful.run(barcodeScanDTO);
            this.dismiss();
        } else {
            this.onError(new Exception("Il barcode scansionato non è valido!"));
        }
    }
}
