package it.integry.integrywmsnative.gest.prod_accettazione_ord_produzione.dialog;

import androidx.lifecycle.MutableLiveData;

import com.annimon.stream.Stream;
import com.annimon.stream.function.Predicate;

import java.util.List;

import it.integry.integrywmsnative.core.utility.UtilityString;
import it.integry.integrywmsnative.gest.accettazione.dto.OrdineAccettazioneInevasoDTO;

public class DialogOrdineProduzioneFiltroAvanzatoViewModel {


    private Predicate<OrdineAccettazioneInevasoDTO> currentNumOrdsPredicate = null;
    private Predicate<OrdineAccettazioneInevasoDTO> currentCodJcomsPredicate = null;

    private List<OrdineAccettazioneInevasoDTO> initialOrderList;
    private final MutableLiveData<List<OrdineAccettazioneInevasoDTO>> currentFilteredOrderList = new MutableLiveData<>();

    public void init(List<OrdineAccettazioneInevasoDTO> initialList) {
        this.initialOrderList = initialList;
        this.currentFilteredOrderList.setValue(this.initialOrderList);
    }

    public MutableLiveData<List<OrdineAccettazioneInevasoDTO>> getMutableFilteredOrderList() {
        return this.currentFilteredOrderList;
    }

    public void setNumOrdFilter(String numOrds) {
        if(UtilityString.isNullOrEmpty(numOrds)) currentNumOrdsPredicate = null;
        else {
            String[] numOrdsSplitted = numOrds.split("[,\\ ]");

            try{
                List<Integer> numOrdsInteger = Stream.of(numOrdsSplitted)
                        .filter(x -> !UtilityString.isNullOrEmpty(x))
                        .map(Integer::parseInt).toList();

                currentNumOrdsPredicate = o -> numOrdsInteger.contains(o.getNumero());
            } catch (NumberFormatException ex) {
                currentNumOrdsPredicate = null;
            }
        }
    }

    public void setCodJcomFilter(String codJcom) {
        if(UtilityString.isNullOrEmpty(codJcom)) currentCodJcomsPredicate = null;
        else {
            currentCodJcomsPredicate = o -> o.getCodJcom().toLowerCase().equalsIgnoreCase(codJcom);
        }
    }

    public void applyAllTests() {

        List<OrdineAccettazioneInevasoDTO> returnList = null;

        if (currentNumOrdsPredicate == null &&
                currentCodJcomsPredicate == null
        ) {
            returnList = this.initialOrderList;
        } else {
            Stream<OrdineAccettazioneInevasoDTO> tmpStream = Stream.of(this.initialOrderList)
                    .filter(x ->
                            (currentNumOrdsPredicate == null || (currentNumOrdsPredicate.test(x))) &&
                                    (currentCodJcomsPredicate == null || (currentCodJcomsPredicate.test(x)))
                    );

            returnList = tmpStream.toList();
        }

        this.currentFilteredOrderList.setValue(returnList);
    }

}
