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

import it.integry.barcode_base_android_library.model.BarcodeScanDTO;
import it.integry.integrywmsnative.core.exception.InvalidLineaProdBarcodeException;
import it.integry.integrywmsnative.core.exception.NoResultFromBarcodeException;
import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener;
import it.integry.integrywmsnative.core.model.MtbDepoPosizione;
import it.integry.integrywmsnative.core.utility.UtilityBarcode;
import it.integry.integrywmsnative.core.utility.UtilityPosizione;

public class DialogAskLineaProdViewModel {

    private Listener mListener;

    public void processBarcodeDTO(BarcodeScanDTO data, Runnable onComplete) {
        if (UtilityBarcode.isEtichettaPosizione(data)) {

            MtbDepoPosizione foundPosizione = UtilityPosizione.getFromCache(data.getStringValue());

            if (!foundPosizione.isFlagLineaProduzione()) {
                this.sendError(new InvalidLineaProdBarcodeException(data.getStringValue()));
                onComplete.run();
                return;
            }

            onComplete.run();
            this.sendOnProductionLineSelected(foundPosizione.getPosizione());

        } else {
            this.sendError(new NoResultFromBarcodeException());
            onComplete.run();
        }
    }

    public DialogAskLineaProdViewModel setListener(Listener listener) {
        this.mListener = listener;
        return this;
    }

    private void sendOnLoadingStarted() {
        if (this.mListener != null) mListener.onLoadingStarted();
    }

    private void sendOnLoadingEnded() {
        if (this.mListener != null) mListener.onLoadingEnded();
    }

    private void sendOnProductionLineSelected(String codJfas) {
        if (this.mListener != null) mListener.onProductionLineSelected(codJfas);
    }

    private void sendError(Exception ex) {
        if (this.mListener != null) mListener.onError(ex);
    }

    public interface Listener extends ILoadingListener {
        void onError(Exception ex);
        void onProductionLineSelected(String codJfas);
    }
}