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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.BdfServerEditor;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.groups.GroupDef;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.BdfServerUtils;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import net.mapeadores.util.attr.AttributeChange;
import net.mapeadores.util.attr.AttributeParser;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.LabelChange;


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

    public final static String COMMANDNAME = "GroupChange";
    public final static String COMMANDKEY = "_ CNF-11";
    public final static String NAME_PARAMNAME = "name";
    public final static String TITLE_PARAMPREFIX = "title/";
    public final static String ATTRIBUTES_PARAMNAME = "attributes";
    private GroupDef groupDef;
    private LabelChange groupLabelChange;
    private AttributeChange attributeChange;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        try (EditSession session = startEditSession(Domains.CONFIGURATION, COMMANDNAME)) {
            BdfServerEditor bdfServerEditor = session.getBdfServerEditor();
            BdfServerUtils.changeLabels(bdfServerEditor, groupDef, groupLabelChange);
            if (attributeChange != null) {
                BdfServerUtils.changeAttributes(bdfServerEditor, groupDef, attributeChange);
            }
        }
        setDone("_ done.configuration.groupchange", groupDef.getName());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String name = getMandatory(NAME_PARAMNAME);
        groupDef = bdfServer.getGroupManager().getGroupDef(name);
        if (groupDef == null) {
            throw BdfErrors.unknownParameterValue(NAME_PARAMNAME, name);
        }
        groupLabelChange = requestHandler.getLabelChange(TITLE_PARAMPREFIX);
        String attributes = requestHandler.getTrimedParameter(ATTRIBUTES_PARAMNAME);
        if (!attributes.isEmpty()) {
            attributeChange = AttributeParser.parse(attributes);
        }
    }

}
