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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.roles.Role;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.fichotheque.ExistingIdException;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;


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

    public final static String COMMANDNAME = "RoleCreation";
    public final static String COMMANDKEY = "_ ROL-01";
    public final static String NEWROLE_PARAMNAME = "newrole";
    private String newRoleName;

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

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

    @Override
    protected void doCommand() {
        Role role;
        try (EditSession session = startEditSession(Domains.ADMINISTRATION, COMMANDNAME)) {
            try {
                role = session.getBdfServerEditor().getRoleEditor().createRole(newRoleName);
            } catch (ParseException | ExistingIdException e) {
                throw new ShouldNotOccurException("Test done before");
            }
        }
        setDone("_ done.administration.rolecreation", newRoleName);
        putResultObject(ROLE_OBJ, role);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        newRoleName = getMandatory(NEWROLE_PARAMNAME);
        newRoleName = newRoleName.trim();
        if (newRoleName.length() == 0) {
            throw BdfErrors.error("_ error.empty.rolename", newRoleName);
        }
        if (!StringUtils.isTechnicalName(newRoleName, true)) {
            throw BdfErrors.error("_ error.wrong.rolename", newRoleName);
        }
        Role role = bdfServer.getPermissionManager().getRole(newRoleName);
        if (role != null) {
            throw BdfErrors.error("_ error.existing.role", newRoleName);
        }
    }

}
