/* FichothequeLib_Tools - Copyright (c) 2014-2020 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.tools.include;

import java.util.HashMap;
import java.util.Map;
import net.fichotheque.SubsetKey;
import net.fichotheque.include.ExtendedIncludeKey;
import net.fichotheque.include.LiageTest;
import net.mapeadores.util.primitives.Range;
import net.mapeadores.util.primitives.Ranges;


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

    public final static LiageTest ALL_LIAGETEST = new InternalLiageTest(new HashMap<SubsetKey, Object>());
    private final Map<SubsetKey, Object> testMap = new HashMap<SubsetKey, Object>();

    public LiageTestBuilder() {
    }

    public LiageTestBuilder checkIncludeKey(ExtendedIncludeKey includeKey) {
        SubsetKey subsetKey = includeKey.getSubsetKey();
        if (!subsetKey.isCorpusSubset()) {
            return this;
        }
        if ((includeKey.isMaster()) || (includeKey.getMode().length() > 0)) {
            return this;
        }
        int weightFilter = includeKey.getWeightFilter();
        if (weightFilter < 1) {
            testMap.put(subsetKey, Boolean.FALSE);
        } else {
            Object currentValue = testMap.get(subsetKey);
            if ((currentValue == null) || (!currentValue.equals(Boolean.FALSE))) {
                Ranges ranges;
                if ((currentValue != null) && (currentValue instanceof Ranges)) {
                    ranges = (Ranges) currentValue;
                } else {
                    ranges = new Ranges();
                    testMap.put(subsetKey, ranges);
                }
                ranges.addRange(new Range(weightFilter, weightFilter));
            }
        }
        return this;
    }

    public LiageTest toLiageTest() {
        return new InternalLiageTest(testMap);
    }

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


    private static class InternalLiageTest implements LiageTest {

        private final Map<SubsetKey, Object> testMap;

        private InternalLiageTest(Map<SubsetKey, Object> testMap) {
            this.testMap = testMap;
        }

        @Override
        public Object ownsToLiage(SubsetKey corpusKey) {
            Object obj = testMap.get(corpusKey);
            if (obj != null) {
                return obj;
            } else {
                return Boolean.TRUE;
            }
        }

    }

}
