/* BdfServer - Copyright (c) 2025 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.impl;

import fr.exemole.bdfserver.api.managers.JsLibManager;
import fr.exemole.bdfserver.tools.jslib.JsLibConf;
import fr.exemole.bdfserver.tools.jslib.JsLibConfFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import net.mapeadores.util.io.ResourceStorages;
import net.mapeadores.util.jslib.JsLib;
import net.mapeadores.util.jslib.JsLibUtils;
import net.mapeadores.util.text.RelativePath;


/**
 *
 * @author Vincent Calame
 */
class JsLibManagerImpl implements JsLibManager {

    private final static RelativePath JSLIBS_DIR = RelativePath.build("jslibs");
    private final ResourceStorages resourceStorages;
    private final Map<String, List<JsLib>> libByPageMap = new HashMap<String, List<JsLib>>();

    JsLibManagerImpl(ResourceStorages resourceStorages) {
        this.resourceStorages = resourceStorages;
    }

    @Override
    public synchronized void update() {
        SortedMap<String, JsLibConf> confMap = new TreeMap<String, JsLibConf>();
        SortedMap<String, RelativePath> jsLibFolderMap = resourceStorages.listSubFolders(JSLIBS_DIR);
        for (Map.Entry<String, RelativePath> entry : jsLibFolderMap.entrySet()) {
            String name = entry.getKey();
            RelativePath dirPath = entry.getValue();
            JsLibConf jsLibConf = JsLibConfFactory.newInstance(resourceStorages, name, dirPath);
            confMap.put(name, jsLibConf);
        }
        for (JsLibConf jsLibConf : confMap.values()) {
            populateByPage(jsLibConf.getJsLib(), jsLibConf.getPageList());
        }
    }

    @Override
    public List<JsLib> getCustomJsLibList(String page) {
        List<JsLib> list = libByPageMap.get(page);
        if (list != null) {
            return list;
        } else {
            return JsLibUtils.EMPTY_JSLIBLIST;
        }
    }

    private void populateByPage(JsLib jsLib, Collection<String> pages) {
        for (String page : pages) {
            List<JsLib> currentList = libByPageMap.get(page);
            if (currentList == null) {
                currentList = new ArrayList<JsLib>();
                libByPageMap.put(page, currentList);
            }
            currentList.add(jsLib);
        }
    }

}
