/* BdfServer - Copyright (c) 2015-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 fr.exemole.bdfserver.tools.storage;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import net.mapeadores.util.exceptions.NestedIOException;
import net.mapeadores.util.io.DocStream;
import net.mapeadores.util.io.ResourceStorages;
import net.mapeadores.util.jslib.JsAnalyser;
import net.mapeadores.util.localisation.LocalisationUtils;
import net.mapeadores.util.text.RelativePath;


/**
 *
 * @author Vincent Calame
 */
public class ResourceJsAnalyser implements JsAnalyser {

    private final static Set<String> EMPTY_SET = Collections.emptySet();
    private final ResourceStorages resourceStorages;
    private final Map<RelativePath, Set<String>> messageKeyMap = new HashMap<RelativePath, Set<String>>();

    public ResourceJsAnalyser(ResourceStorages resourceStorages) {
        this.resourceStorages = resourceStorages;
    }

    @Override
    public Set<String> getJsMessageKeySet(RelativePath relativePath) {
        Set<String> set = messageKeyMap.get(relativePath);
        if (set == null) {
            set = buildSet(relativePath);
        }
        return set;
    }

    @Override
    public synchronized void clearCache() {
        messageKeyMap.clear();
    }

    private synchronized Set<String> buildSet(RelativePath relativePath) {
        Set<String> set = messageKeyMap.get(relativePath);
        if (set != null) {
            return set;
        }
        DocStream docStream = resourceStorages.getResourceDocStream(relativePath);
        if (docStream != null) {
            try (InputStream is = docStream.getInputStream()) {
                set = Collections.unmodifiableSet(LocalisationUtils.scanMessageKeys(is, docStream.getCharset()));
            } catch (IOException ioe) {
                throw new NestedIOException(ioe);
            }
        } else {
            set = EMPTY_SET;
        }
        messageKeyMap.put(relativePath, set);
        return set;
    }

}
