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

import androidx.databinding.ObservableField;

import javax.inject.Inject;

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.core.di.BindableString;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.rest.consumers.ArticoloRESTConsumer;
import it.integry.integrywmsnative.core.utility.UtilityBarcode;

public class DialogAskUnknownBarcodeNotesViewModel {
    public ObservableField<String> userNotes = new ObservableField<>();
    public BindableString userNotesErrorMessage = new BindableString();

    private ArticoloRESTConsumer articoloRESTConsumer;

    private String unknownBarcode;

    @Inject
    public DialogAskUnknownBarcodeNotesViewModel(ArticoloRESTConsumer articoloRESTConsumer) {
        this.articoloRESTConsumer = articoloRESTConsumer;
    }

    public void init(String unknownBarcode) {
        this.unknownBarcode = unknownBarcode;
    }

    public void processBarcodeDTO(BarcodeScanDTO barcodeScanDTO, Runnable onComplete, RunnableArgs<Exception> onFailed) {
        if (UtilityBarcode.isEtichettaAnonima(barcodeScanDTO) ||
                UtilityBarcode.isEtichettaPosizione(barcodeScanDTO) ||
                UtilityBarcode.isEtichetta128(barcodeScanDTO) ||
                UtilityBarcode.isEanPeso(barcodeScanDTO)) {

            onFailed.run(new Exception("E' necessario scansionare un'etichetta EAN13 per procedere"));
        } else {
            this.loadArticolo(barcodeScanDTO.getStringValue(), onComplete, onFailed);

        }
    }

    private void loadArticolo(String stringValue, Runnable onComplete, RunnableArgs<Exception> onFailed) {
        this.articoloRESTConsumer.searchByBarcode(stringValue, mtbAarts -> {

            if(mtbAarts == null || mtbAarts.isEmpty()) {
                onFailed.run(new Exception("Nessun articolo trovato con il barcode: " + stringValue));
                return;
            }

            if(mtbAarts.size() > 1) {
                onFailed.run(new Exception("Sono stati trovati " + mtbAarts.size() + " articoli agganciati al barcode: " + stringValue));
                return;
            }

            var mtbAart = mtbAarts.get(0);

            articoloRESTConsumer.updateBarcodeImballo(mtbAart.getCodMart(), unknownBarcode, onComplete, onFailed);
        }, onFailed);
    }

    public boolean validateInput() {
        final boolean emptyUserNotes = userNotes.get() != null && !userNotes.get().isEmpty() && !userNotes.get().isBlank();

        if(!emptyUserNotes)
            userNotesErrorMessage.set("E' necessario scrivere delle note");


        return emptyUserNotes;
    }
}