/* BdfServer_Commands - Copyright (c) 2012-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.configuration.PathConfiguration;
import fr.exemole.bdfserver.tools.configuration.PathConfigurationBuilder;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.runners.BalayageRunner;
import net.fichotheque.exportation.balayage.BalayageDescription;
import net.fichotheque.utils.BalayageUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "BalayageRun";
    public final static String MODE_PARAMNAME = "mode";
    private BalayageDescription balayageDescription;
    private String mode;

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

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

    @Override
    protected void doCommand() {
        PathConfiguration pathConfiguration = PathConfigurationBuilder.build(bdfServer);
        BalayageRunner.Result result = BalayageRunner.run(balayageDescription, mode, bdfServer, pathConfiguration);
        putResultObject(BALAYAGEDESCRIPTION_OBJ, balayageDescription);
        if (result.hasError()) {
            setCommandMessage(result.getError());
        } else {
            putResultObject(BALAYAGELOG_OBJ, result.getBalayageLog());
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        getPermissionChecker()
                .checkAdmin("balayagerun");
        balayageDescription = requestHandler.getMandatoryBalayageDescription();
        mode = requestHandler.getTrimedParameter(MODE_PARAMNAME);
        if (mode.isEmpty()) {
            mode = null;
        } else if (!BalayageUtils.containsMode(balayageDescription.getBalayageDef(), mode)) {
            throw BdfErrors.unknownParameterValue(MODE_PARAMNAME, mode);
        }
    }

}
