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.interfaces.viewmodel_listeners.IOrdersLoadingListener;
import it.integry.integrywmsnative.core.rest.consumers.MesRESTConsumer;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.gest.prod_versamento_materiale.dto.OrdineLavorazioneDTO;
import it.integry.integrywmsnative.gest.spedizione.exceptions.OrdersLoadException;

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 refreshOrderList() {
        new Thread(this::sendOnOrdersLoadingStarted).start();
        String codAnag = SettingsManager.iDB().getFilterFornitoreProd();
        this.mMesRESTConsumer.getOrdiniLavorazione("I", null, codAnag, ordiniLavorazioneList -> {
            this.mOrdiniLavorazioneAperti.postValue(ordiniLavorazioneList);
            this.sendOnOrdersLoadingEnded();
        }, ex -> this.sendError(new OrdersLoadException(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 sendOnOrdersLoadingStarted() {
        if (this.mListener != null) mListener.onOrderLoadingStarted();
    }

    private void sendOnOrdersLoadingEnded() {
        if (this.mListener != null) mListener.onOrderLoadingEnded();
    }

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


    public interface Listener extends ILoadingListener, IOrdersLoadingListener {

        void onDataSaved();

        void onError(Exception ex);

    }


}