package it.integry.integrywmsnative.core.rest.consumers;

import com.annimon.stream.Optional;
import com.annimon.stream.Stream;

import java.util.List;

import javax.inject.Singleton;

import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.model.MtbAart;
import it.integry.integrywmsnative.core.model.MtbDepoPosizione;
import it.integry.integrywmsnative.core.model.MvwSitArtUdcDetInventario;
import it.integry.integrywmsnative.core.rest.RESTBuilder;
import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Singleton
public class GiacenzaRESTConsumer extends _BaseRESTConsumer {

    private final SystemRESTConsumer mSystemRESTConsumer;
    private final ArticoloRESTConsumer mArticoloRESTConsumer;

    public GiacenzaRESTConsumer(SystemRESTConsumer systemRESTConsumer, ArticoloRESTConsumer articoloRESTConsumer) {
        this.mSystemRESTConsumer = systemRESTConsumer;
        this.mArticoloRESTConsumer = articoloRESTConsumer;

    }

    public void getGiacenzeInPosizione(MtbDepoPosizione posizione, RunnableArgs<List<MvwSitArtUdcDetInventario>> onComplete, RunnableArgs<Exception> onFailed) {
        GiacenzaRESTConsumerService giacenzaRESTConsumerService = RESTBuilder.getService(GiacenzaRESTConsumerService.class);
        giacenzaRESTConsumerService.retrieveAvailableItems(posizione.getPosizione()).enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<ServiceRESTResponse<List<MvwSitArtUdcDetInventario>>> call, Response<ServiceRESTResponse<List<MvwSitArtUdcDetInventario>>> response) {
                analyzeAnswer(response, "getGiacenzeInPosizione", inventarioList -> {

                    List<String> codMarts = Stream.of(inventarioList)
                            .map(x -> x.getCodMart().trim())
                            .toList();

                    mArticoloRESTConsumer.getByCodMarts(codMarts, mtbAarts -> {
                        for (var row : inventarioList) {

                            MtbAart foundMtbAart = null;
                            Optional<MtbAart> mtbAartOpt = Stream.of(mtbAarts)
                                    .filter(x -> x.getCodMart().equalsIgnoreCase(row.getCodMart()))
                                    .findFirst();

                            if (mtbAartOpt.isPresent()) {
                                foundMtbAart = mtbAartOpt.get();
                            }

                            row.setMtbAart(foundMtbAart);
                        }

                        onComplete.run(inventarioList);
                    }, onFailed);
                }, onFailed);
            }

            @Override
            public void onFailure(Call<ServiceRESTResponse<List<MvwSitArtUdcDetInventario>>> call, Throwable t) {
                onFailed.run(new Exception(t));
            }
        });
    }


}
