package it.integry.integrywmsnative.view.dialogs.scan_art;

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 com.annimon.stream.Stream;

import org.jetbrains.annotations.NotNull;

import javax.inject.Inject;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.MainApplication;
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.expansion.RunnableArgssss;
import it.integry.integrywmsnative.core.model.MtbAart;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.core.model.MtbDepoPosizione;
import it.integry.integrywmsnative.core.rest.model.Ean128Model;
import it.integry.integrywmsnative.databinding.DialogScanArtBinding;
import it.integry.integrywmsnative.view.dialogs.DialogConsts;
import it.integry.integrywmsnative.view.dialogs.choose_batch_lot.choose_art_from_lista_mtb_colr.DialogChooseArtFromListaMtbColrView;

public class DialogScanArtView extends BaseDialogFragment implements DialogScanArtViewModel.Listener {

    @Inject
    DialogScanArtViewModel mViewModel;

    private final boolean mForceOnlyUL;

    private DialogScanArtBinding mBindings;

    private int mBarcodeScannerIstanceID;

    private RunnableArgssss<DialogConsts.Results, MtbAart, Ean128Model, MtbColr> onPickingCompleted = null;
    private RunnableArgs<MtbDepoPosizione> onMagazzinoAutomaticoPickingRequest = null;


    public static DialogScanArtView newInstance(boolean forceOnlyUL, @NotNull RunnableArgssss<DialogConsts.Results, MtbAart, Ean128Model, MtbColr> onPickingCompleted, RunnableArgs<MtbDepoPosizione> onMagazzinoAutomaticoPickingRequest) {
        return new DialogScanArtView(forceOnlyUL, onPickingCompleted, onMagazzinoAutomaticoPickingRequest);
    }

    private DialogScanArtView(boolean forceOnlyUL, RunnableArgssss<DialogConsts.Results, MtbAart, Ean128Model, MtbColr> onItemChoosed, RunnableArgs<MtbDepoPosizione> onMagazzinoAutomaticoPickingRequest) {
        super();
        mForceOnlyUL = forceOnlyUL;
        onPickingCompleted = onItemChoosed;
        this.onMagazzinoAutomaticoPickingRequest = onMagazzinoAutomaticoPickingRequest;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        this.initBarcode();

        mBindings = DialogScanArtBinding.inflate(inflater, container, false);
        mBindings.setLifecycleOwner(this);

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

        this.mViewModel
                .setForceOnlyUL(mForceOnlyUL)
                .setListener(this);

        getDialog().setCanceledOnTouchOutside(false);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        mBindings.buttonNo.setOnClickListener(v -> {
            onPickingCompleted.run(DialogConsts.Results.ABORT, null, null, null);
            dismiss();
        });

        return mBindings.getRoot();
    }


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


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


    private final RunnableArgs<BarcodeScanDTO> onScanSuccessfull = data -> {
        this.onLoadingStarted();

        this.mViewModel.processBarcodeDTO(data, (status, mtbAart, ean128Model, mtbColrList) -> {

            var filteredMtbColrList = mtbColrList;

            if (mtbAart != null && filteredMtbColrList != null) {
                filteredMtbColrList = Stream.of(filteredMtbColrList)
                        .filter(x -> x.getCodMart().equalsIgnoreCase(mtbAart.getCodMart()))
                        .toList();
            }

            if (filteredMtbColrList != null && filteredMtbColrList.size() > 1) {
                DialogChooseArtFromListaMtbColrView.make(getActivity(), filteredMtbColrList, mtbColrChose -> {
                    onPickingCompleted.run(status, mtbAart, ean128Model, mtbColrChose);
                }).show();

            } else if (filteredMtbColrList != null && filteredMtbColrList.size() == 1) {
                onPickingCompleted.run(status, mtbAart, ean128Model, filteredMtbColrList.get(0));

            } else {
                onPickingCompleted.run(status, mtbAart, ean128Model, null);
            }


            this.onLoadingEnded();

            dismiss();
        }, pickMagazzinoAutomaticoPosizione -> {
            this.onMagazzinoAutomaticoPickingRequest.run(pickMagazzinoAutomaticoPosizione);

            this.onLoadingEnded();
            dismiss();
        });
    };


    @Override
    public void onError(Exception ex) {
        super.onError(ex);
        BarcodeManager.enable();
    }
}
