package it.integry.integrywmsnative.gest.prod_rientro_merce;

import androidx.lifecycle.MutableLiveData;

import java.util.List;

import javax.inject.Inject;

import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener;
import it.integry.integrywmsnative.core.rest.consumers.MesRESTConsumer;
import it.integry.integrywmsnative.gest.picking_resi.exceptions.DocumentsLoadException;
import it.integry.integrywmsnative.gest.prod_versamento_materiale.dto.OrdineLavorazioneDTO;

public class ProdRientroMerceViewModel {


    private final MutableLiveData<List<OrdineLavorazioneDTO>> mOrdiniLavorazioneAperti = new MutableLiveData<>();

    private Listener mListener;

    private final MesRESTConsumer mMesRESTConsumer;

    @Inject
    public ProdRientroMerceViewModel(MesRESTConsumer mesRESTConsumer) {
        this.mMesRESTConsumer = mesRESTConsumer;
    }

    public void init() {
        new Thread(this::sendOnLoadingStarted).start();

        this.mMesRESTConsumer.getOrdiniLavorazione("I", null, ordiniLavorazioneList -> {
            this.mOrdiniLavorazioneAperti.postValue(ordiniLavorazioneList);
            this.sendOnLoadingEnded();
        }, ex -> this.sendError(new DocumentsLoadException(ex)));
    }

    public MutableLiveData<List<OrdineLavorazioneDTO>> getOrdiniLavorazioneAperti() {
        return mOrdiniLavorazioneAperti;
    }

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


    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 interface Listener extends ILoadingListener {

        void onDataSaved();

        void onError(Exception ex);

    }


}