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


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

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

    public IllustrationConditionBuilder() {

    }

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

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

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

    public IllustrationCondition toIllustrationCondition() {
        List<IllustrationCondition.Entry> finalEntryList = new EntryList(entryList.toArray(new IllustrationCondition.Entry[entryList.size()]));
        return new InternalIllustrationCondition(logicalOperator, finalEntryList);
    }

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


    private static class InternalIllustrationCondition implements IllustrationCondition {

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

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

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

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

    }


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

        private final IllustrationCondition.Entry[] array;

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

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

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

    }

}
