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


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

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

    public DocumentConditionBuilder() {

    }

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

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

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

    public DocumentCondition toDocumentCondition() {
        List<DocumentCondition.Entry> finalEntryList = new EntryList(entryList.toArray(new DocumentCondition.Entry[entryList.size()]));
        return new InternalDocumentCondition(logicalOperator, finalEntryList);
    }

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


    private static class InternalDocumentCondition implements DocumentCondition {

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

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

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

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

    }


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

        private final DocumentCondition.Entry[] array;

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

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

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

    }

}
