/* UtilLib - Copyright (c) 2018 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.mapeadores.util.text;

import java.util.SortedMap;
import java.util.TreeMap;
import net.mapeadores.util.localisation.Lang;


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

    private final SortedMap<String, PhraseCache> cacheMap = new TreeMap<String, PhraseCache>();
    private Phrases cachedPhrases;

    public PhrasesCache() {

    }

    public synchronized void clear() {
        cacheMap.clear();
        cachedPhrases = null;
    }

    public synchronized void putLabels(String name, Labels labels) {
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        PhraseCache phraseCache = cacheMap.get(name);
        if (phraseCache == null) {
            phraseCache = new PhraseCache(name);
            cacheMap.put(name, phraseCache);
        }
        cachedPhrases = null;
        phraseCache.putLabels(labels);
    }

    public synchronized boolean putLabel(String name, Label label) {
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        PhraseCache phraseCache = cacheMap.get(name);
        if (phraseCache == null) {
            phraseCache = new PhraseCache(name);
            cacheMap.put(name, phraseCache);
        }
        cachedPhrases = null;
        return phraseCache.putLabel(label);
    }

    public synchronized boolean removeLabel(String name, Lang lang) {
        if (name == null) {
            throw new IllegalArgumentException("name is null");
        }
        PhraseCache phraseCache = cacheMap.get(name);
        if (phraseCache == null) {
            return false;
        }
        cachedPhrases = null;
        boolean done = phraseCache.removeLabel(lang);
        if (phraseCache.isEmpty()) {
            cacheMap.remove(name);
        }
        return done;
    }

    public Phrases getPhrases() {
        Phrases phrases = cachedPhrases;
        if (phrases == null) {
            phrases = cache();
        }
        return phrases;
    }

    private synchronized Phrases cache() {
        Phrases cache = PhrasesBuilder.toPhrases(cacheMap);
        cachedPhrases = cache;
        return cache;
    }

}
