package it.integry.integrywmsnative.gest.lista_bancali;


import androidx.databinding.ObservableArrayList;

import javax.inject.Inject;

import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener;
import it.integry.integrywmsnative.core.model.MtbColr;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.rest.consumers.ColliMagazzinoRESTConsumer;

public class ListaBancaliViewModel {

    private final ColliMagazzinoRESTConsumer mColliMagazzinoRESTConsumer;

    private Listener mListener;

    @Inject
    public ListaBancaliViewModel(ColliMagazzinoRESTConsumer colliMagazzinoRESTConsumer) {
        this.mColliMagazzinoRESTConsumer = colliMagazzinoRESTConsumer;
    }


    public void dispatchMtbColt(MtbColt mtbColtToDispatch, boolean onlyResiduo, RunnableArgs<MtbColt> onComplete) {
        this.sendOnLoadingStarted();

        new Thread(() -> {
            mColliMagazzinoRESTConsumer.getByTestata(mtbColtToDispatch, onlyResiduo, false, mtbColt -> {
                this.sendOnLoadingEnded();

                ObservableArrayList<MtbColr> mtbColrObservableArrayList = new ObservableArrayList<>();
                if(mtbColt != null && mtbColt.getMtbColr() != null) mtbColrObservableArrayList.addAll(mtbColt.getMtbColr());
                mtbColtToDispatch.setMtbColr(mtbColrObservableArrayList);

                onComplete.run(mtbColtToDispatch);
            }, this::sendError);

        }).start();
    }


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

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

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

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

    public interface Listener extends ILoadingListener {

        void onError(Exception ex);

    }

}
