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

import javax.inject.Inject;

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

public class DialogBindProductBarcodeWithPackageViewModel {

    private ArticoloRESTConsumer articoloRESTConsumer;

    private String unknownBarcode;

    @Inject
    public DialogBindProductBarcodeWithPackageViewModel(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);
    }
}