package it.integry.integrywmsnative.gest.accettazione_ordine_inevaso.rest;

import android.text.TextUtils;

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

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import it.integry.integrywmsnative.core.REST.consumers.ISimpleOperationCallback;
import it.integry.integrywmsnative.core.REST.consumers.SystemRESTConsumer;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.model.MtbColt;
import it.integry.integrywmsnative.core.utility.UtilityDate;
import it.integry.integrywmsnative.core.utility.UtilityLogger;
import it.integry.integrywmsnative.gest.accettazione.dto.OrdineAccettazioneDTO;

public class OrdineAccettazioneInevasoRESTConsumerService {

    public static void getBancaliGiaRegistrati(List<OrdineAccettazioneDTO> ordiniToShow, RunnableArgs<List<MtbColt>> onComplete, RunnableArgs<Exception> onFailed) throws Exception {

        List<String> colliWhereCond = new ArrayList<>();


        Stream.of(ordiniToShow).forEach(x -> {
            try {
                Date date = UtilityDate.recognizeDate(x.data);
                String dateString = UtilityDate.formatDate(date, "yyyy/MM/dd");

                if (!colliWhereCond.contains(x.gestione + " " + dateString + " " + x.numero)) {
                    colliWhereCond.add(x.gestione + " " + dateString + " " + x.numero);
                }
            } catch (Exception ex){
                UtilityLogger.errorMe(ex);
            }
        });


        String colliINCondition = "";

        for(int i = 0; i < colliWhereCond.size(); i ++){
            colliINCondition += "'" + colliWhereCond.get(i) + "'";

            if(i < (colliWhereCond.size()-1)) colliINCondition += ",";
        }



        String sql = "select distinct mtb_colt.* " +
                "from mtb_colt, mtb_colr " +
                "where mtb_colt.gestione = mtb_colr.gestione and " +
                "mtb_colt.ser_collo = mtb_colr.ser_collo and " +
                "mtb_colt.data_collo = mtb_colr.data_collo and " +
                "mtb_colt.num_collo = mtb_colr.num_collo AND " +
                "mtb_colt.gestione + ' ' + convert(varchar(15), mtb_colr.data_ord, 111) + ' ' + convert(varchar, mtb_colr.num_ord) IN (" + colliINCondition +
                ") and mtb_colt.data_doc is null ";


        Type typeOfObjectsList = new TypeToken<ArrayList<MtbColt>>() {}.getType();
        SystemRESTConsumer.processSql(sql, typeOfObjectsList, new ISimpleOperationCallback<List<MtbColt>>() {
            @Override
            public void onSuccess(List<MtbColt> value) {
                if(onComplete != null) onComplete.run(value);
            }

            @Override
            public void onFailed(Exception ex) {
                if(onFailed != null) onFailed.run(ex);
            }
        });

    }

}
