/* 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.MotcleCondition;
import net.mapeadores.util.conditions.ConditionsConstants;


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

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

    public MotcleConditionBuilder() {

    }

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

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

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

    public MotcleCondition toMotcleCondition() {
        List<MotcleCondition.Entry> finalEntryList = new EntryList(entryList.toArray(new MotcleCondition.Entry[entryList.size()]));
        return new InternalMotcleCondition(logicalOperator, finalEntryList);
    }

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


    private static class InternalMotcleCondition implements MotcleCondition {

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

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

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

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

    }


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

        private final MotcleCondition.Entry[] array;

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

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

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

    }

}
