package it.integry.integrywmsnative.gest.prod_fabbisogno_linee_prod;

import com.annimon.stream.Stream;

import java.util.Date;
import java.util.List;

import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.interfaces.viewmodel_listeners.ILoadingListener;
import it.integry.integrywmsnative.gest.prod_fabbisogno_linee_prod.dto.ProdFabbisognoLineeProdDTO;
import it.integry.integrywmsnative.gest.prod_fabbisogno_linee_prod.rest.ProdFabbisognoLineeProdRESTConsumer;

public class ProdFabbisognoLineeProdViewModel {

    private final ProdFabbisognoLineeProdRESTConsumer mProdFabbisognoLineeProdRESTConsumer;

    private Listener mListener;

    public ProdFabbisognoLineeProdViewModel(ProdFabbisognoLineeProdRESTConsumer prodFabbisognoLineeProdRESTConsumer) {
        this.mProdFabbisognoLineeProdRESTConsumer = prodFabbisognoLineeProdRESTConsumer;
    }

    public void init() {

    }


    public void loadFabbisogno(Date startDate, Date endDate, String codMdep, RunnableArgs<List<ProdFabbisognoLineeProdDTO>> onComplete) {
        this.sendOnLoadingStarted();

        this.mProdFabbisognoLineeProdRESTConsumer.loadFabbisogno(startDate, endDate, codMdep, jtbFasi -> {
            if (jtbFasi != null) Stream.of(jtbFasi)
                    .forEach(x -> x
                            .setDataInizio(startDate)
                            .setDataFine(endDate));

            this.sendOnLoadingEnded();
            onComplete.run(jtbFasi);
        }, this::sendError);
    }


    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 void setListener(Listener listener) {
        this.mListener = listener;
    }

    public interface Listener extends ILoadingListener {

        void onError(Exception ex);

    }

}
