/* 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.exportation;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.managers.AccessManager;
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;


/**
 *
 * @author Vincent Calame
 */
public class AccessChangeCommand extends AbstractDefChangeCommand {

    public final static String COMMANDNAME = "AccessChange";
    public final static String COMMANDKEY = "_ EXP-63";
    public final static String TABLEEXPORTNAME_PARAMNAME = "tableexportname";
    public final static String TYPE_PARAMNAME = "type";
    public final static String TOKEN_PARAMNAME = "token";
    private AccessDef accessDef;

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

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

    @Override
    protected void doCommand() {
        AccessManager accessManager = bdfServer.getAccessManager();
        accessManager.putAccessDef(accessDef);
        putResultObject(ACCESSDEF_OBJ, accessDef);
        setDone("_ done.exportation.accesschange", accessDef.getName());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        AccessDef currentAccessDef = requestHandler.getMandatoryAccessDef();
        String type = getType();
        String token = "";
        if (type.equals(AccessDef.TOKEN_ACCESS)) {
            token = requestHandler.getTrimedParameter(TOKEN_PARAMNAME);
            if (token.isEmpty()) {
                throw BdfErrors.emptyMandatoryParameter(TOKEN_PARAMNAME);
            }
        }
        String tableExportName = getMandatory(TABLEEXPORTNAME_PARAMNAME);
        AccessDefBuilder accessDefBuilder = AccessDefBuilder.init(currentAccessDef.getName())
                .setType(type)
                .setToken(token)
                .setTableExportName(tableExportName);
        checkSelectionOptions(accessDefBuilder.getSelectionOptionsBuilder());
        checkDefBuilder(accessDefBuilder);
        this.accessDef = accessDefBuilder.toAccessDef();
    }

    private String getType() throws ErrorMessageException {
        String type = getMandatory(TYPE_PARAMNAME);
        try {
            return AccessDef.checkType(type);
        } catch (IllegalArgumentException iae) {
            throw BdfErrors.unknownParameterValue(TYPE_PARAMNAME, type);
        }
    }

}
