/* BdfServer_Commands - Copyright (c) 2010-2023 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.commands.configuration;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.subsettree.SubsetTree;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.subsettree.TreeParser;
import net.fichotheque.SubsetKey;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


/**
 *
 * @author Vincent Calame
 */
public class SubsetTreeCommand extends AbstractBdfCommand {

    public final static String COMMANDNAME = "SubsetTree";
    public final static String CORPUS_COMMANDKEY = "_ CNF-13";
    public final static String THESAURUS_COMMANDKEY = "_ CNF-14";
    public final static String SPHERE_COMMANDKEY = "_ CNF-15";
    public final static String ALBUM_COMMANDKEY = "_ CNF-16";
    public final static String ADDENDA_COMMANDKEY = "_ CNF-17";
    public final static String CATEGORY_PARAMNAME = "category";
    public final static String TREE_PARAMNAME = "tree";
    private String treeString;
    private short category;

    public SubsetTreeCommand(BdfServer bdfServer, RequestMap requestMap) {
        super(bdfServer, requestMap);
    }

    @Override
    public boolean needSynchronisation() {
        return true;
    }

    @Override
    protected void doCommand() throws ErrorMessageException {
        SubsetTree subsetTree = TreeParser.parse(bdfServer, treeString, category);
        try (EditSession session = startEditSession(Domains.CONFIGURATION, COMMANDNAME)) {
            session.getBdfServerEditor().setSubsetTree(category, subsetTree);
        }
        setDone("_ done.configuration.subsettree");
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String categoryString = getMandatory(CATEGORY_PARAMNAME);
        try {
            category = SubsetKey.categoryToShort(categoryString);
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.unknownParameterValue(CATEGORY_PARAMNAME, categoryString);
        }
        treeString = getMandatory(TREE_PARAMNAME);
    }

}
