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

import com.annimon.stream.Optional;
import com.annimon.stream.Stream;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
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.utility.UtilityQuery;

@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) {

        HashMap<String, Object> params = new HashMap<>();
        params.put("posizione", posizione.getPosizione());
        String whereCond = UtilityQuery.concatFieldsInWhereCond(params);
        String query = "SELECT * from mvw_sitart_udc_det_inventario" +
                "  WHERE " + whereCond;


        Type typeOfObjectsList = new TypeToken<ArrayList<MvwSitArtUdcDetInventario>>() {
        }.getType();
        this.mSystemRESTConsumer.<ArrayList<MvwSitArtUdcDetInventario>>processSql(query, typeOfObjectsList, 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);
    }


}
