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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.managers.AccessManager;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import net.fichotheque.exportation.access.AccessDef;
import net.fichotheque.tools.exportation.access.AccessDefBuilder;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;


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

    public final static String COMMANDNAME = "AccessCreation";
    public final static String COMMANDKEY = "_ EXP-61";
    public final static String NEWACCESS_PARAMNAME = "newaccess";
    private String newAccessName;

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

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

    @Override
    protected void doCommand() {
        AccessManager accessManager = bdfServer.getAccessManager();
        AccessDef accessDef = AccessDefBuilder.init(newAccessName).toAccessDef();
        accessManager.putAccessDef(accessDef);
        putResultObject(ACCESSDEF_OBJ, accessDef);
        setDone("_ done.exportation.accesscreation", newAccessName);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        newAccessName = getMandatory(NEWACCESS_PARAMNAME);
        if (newAccessName.length() == 0) {
            throw BdfErrors.error("_ error.empty.accessname");
        }
        AccessManager accessManager = bdfServer.getAccessManager();
        AccessDef accessDef = accessManager.getAccessDef(newAccessName);
        if (accessDef != null) {
            throw BdfErrors.error("_ error.existing.access", newAccessName);
        }
        if (!StringUtils.isTechnicalName(newAccessName, true)) {
            throw BdfErrors.error("_ error.wrong.accessname", newAccessName);
        }
    }

}
