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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.managers.SelectionManager;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfCommandUtils;
import net.fichotheque.selection.SelectionDef;
import net.fichotheque.tools.selection.SelectionDefBuilder;
import net.mapeadores.util.attr.AttributeParser;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.Label;
import net.mapeadores.util.text.LabelChange;


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

    public final static String COMMANDNAME = "SelectionDefChange";
    public final static String COMMANDKEY = "_ EXP-03";
    public final static String QUERY_XML_PARAMNAME = "query_xml";
    public final static String TITLE_PARAMPREFIX = "title/";
    public final static String ATTRIBUTES_PARAMNAME = "attributes";
    private SelectionDef selectionDef;

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

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

    @Override
    protected void doCommand() {
        SelectionManager selectionManager = bdfServer.getSelectionManager();
        selectionManager.putSelectionDef(selectionDef);
        putResultObject(SELECTIONDEF_OBJ, selectionDef);
        setDone("_ done.selection.selectiondefchange", selectionDef.getName());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        SelectionDef currentSelectionDef = requestHandler.getMandatorySelectionDef();
        SelectionDefBuilder selectionDefBuilder = SelectionDefBuilder.init(currentSelectionDef.getName(), currentSelectionDef.getAttributes());
        BdfCommandUtils.parseQueries(fichotheque, getMandatory(QUERY_XML_PARAMNAME), selectionDefBuilder.getFichothequeQueriesBuilder());
        LabelChange labelChange = requestHandler.getLabelChange(TITLE_PARAMPREFIX);
        for (Label label : labelChange.getChangedLabels()) {
            selectionDefBuilder.putLabel(label);
        }
        String attributes = requestHandler.getTrimedParameter(ATTRIBUTES_PARAMNAME);
        if (!attributes.isEmpty()) {
            selectionDefBuilder.getAttributesBuilder().changeAttributes(AttributeParser.parse(attributes));
        }
        this.selectionDef = selectionDefBuilder.toSelectionDef();
    }

}
