/* FichothequeLib_API - Copyright (c) 2011-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.utils.selection;

import java.util.HashMap;
import java.util.Map;
import net.fichotheque.SubsetKey;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.Thesaurus;
import net.mapeadores.util.primitives.Ranges;


/**
 *
 * @author Vincent Calame
 */
class MotcleRangeTestCache {

    private final Map<SubsetKey, Map<Integer, Boolean>> cacheMap = new HashMap<SubsetKey, Map<Integer, Boolean>>();
    private Map<Integer, Boolean> currentMap;
    private Thesaurus currentThesaurus;
    private final Ranges idRanges;
    private final Ranges levelRanges;

    MotcleRangeTestCache(Ranges levelRanges, Ranges idRanges) {
        this.levelRanges = levelRanges;
        this.idRanges = idRanges;
    }

    public void setCurrentThesaurus(Thesaurus thesaurus) {
        currentMap = cacheMap.get(thesaurus.getSubsetKey());
        if (currentMap == null) {
            currentMap = new HashMap<Integer, Boolean>();
            cacheMap.put(thesaurus.getSubsetKey(), currentMap);
        }
        currentThesaurus = thesaurus;
    }

    public boolean isSelected(Motcle motcle) {
        int id = motcle.getId();
        Boolean b = currentMap.get(id);
        if (b == null) {
            if (isRangeSelected(motcle)) {
                b = Boolean.TRUE;
            } else {
                b = Boolean.FALSE;
            }
            currentMap.put(id, b);
        }
        return b;
    }

    private boolean isRangeSelected(Motcle motcle) {
        if (levelRanges != null) {
            if (!levelRanges.contains(motcle.getLevel())) {
                return false;
            }
        }
        if (idRanges != null) {
            if (!idRanges.contains(motcle.getId())) {
                return false;
            }
        }
        return true;
    }

}
