/* FichothequeLib_API - Copyright (c) 2021-2022 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.fichotheque.utils.selection;

import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
import java.util.RandomAccess;
import net.fichotheque.selection.FicheCondition;
import net.mapeadores.util.conditions.ConditionsConstants;


/**
 *
 * @author Vincent Calame
 */
public class FicheConditionBuilder {

    private final List<FicheCondition.Entry> entryList = new ArrayList<FicheCondition.Entry>();
    private String logicalOperator = ConditionsConstants.LOGICALOPERATOR_AND;

    public FicheConditionBuilder() {

    }

    public boolean isEmpty() {
        return (entryList.isEmpty());
    }

    public FicheConditionBuilder setLogicalOperator(String logicalOperator) {
        this.logicalOperator = logicalOperator;
        return this;
    }

    public FicheConditionBuilder addEntry(FicheCondition.Entry entry) {
        if (entry == null) {
            throw new IllegalArgumentException("entry is null");
        }
        entryList.add(entry);
        return this;
    }

    public FicheCondition toFicheCondition() {
        List<FicheCondition.Entry> finalEntryList = new EntryList(entryList.toArray(new FicheCondition.Entry[entryList.size()]));
        return new InternalFicheCondition(logicalOperator, finalEntryList);
    }

    public static FicheConditionBuilder init() {
        return new FicheConditionBuilder();
    }


    private static class InternalFicheCondition implements FicheCondition {

        private final String logicalOperator;
        private final List<FicheCondition.Entry> entryList;

        private InternalFicheCondition(String logicalOperator, List<FicheCondition.Entry> entryList) {
            this.logicalOperator = logicalOperator;
            this.entryList = entryList;
        }

        @Override
        public String getLogicalOperator() {
            return logicalOperator;
        }

        @Override
        public List<FicheCondition.Entry> getEntryList() {
            return entryList;
        }

    }


    private static class EntryList extends AbstractList<FicheCondition.Entry> implements RandomAccess {

        private final FicheCondition.Entry[] array;

        private EntryList(FicheCondition.Entry[] array) {
            this.array = array;
        }

        @Override
        public int size() {
            return array.length;
        }

        @Override
        public FicheCondition.Entry get(int index) {
            return array[index];
        }

    }

}
