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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.managers.ScrutariExportManager;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.fichotheque.exportation.scrutari.ScrutariExportDef;
import net.fichotheque.metadata.FichothequeMetadata;
import net.fichotheque.tools.exportation.scrutari.ScrutariExportDefBuilder;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "ScrutariExportCreation";
    public final static String COMMANDKEY = "_ EXP-21";
    public final static String NEWSCRUTARIEXPORT_PARAMNAME = "newscrutariexport";
    private String newScrutariExportName;

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

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

    @Override
    protected void doCommand() {
        ScrutariExportManager scrutariExportManager = bdfServer.getScrutariExportManager();
        FichothequeMetadata fichothequeMetadata = fichotheque.getFichothequeMetadata();
        ScrutariExportDef scrutariExportDef = ScrutariExportDefBuilder.init(newScrutariExportName, fichothequeMetadata.getAuthority(), fichothequeMetadata.getBaseName()).toScrutariExportDef();
        scrutariExportManager.putScrutariExportDef(scrutariExportDef);
        putResultObject(SCRUTARIEXPORTDEF_OBJ, scrutariExportDef);
        setDone("_ done.exportation.scrutariexportcreation", newScrutariExportName);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        newScrutariExportName = getMandatory(NEWSCRUTARIEXPORT_PARAMNAME).trim();
        if (newScrutariExportName.length() == 0) {
            throw BdfErrors.error("_ error.empty.exportname");
        }
        ScrutariExportDef scrutariExportDef = bdfServer.getScrutariExportManager().getScrutariExportDef(newScrutariExportName);
        if (scrutariExportDef != null) {
            throw BdfErrors.error("_ error.existing.scrutariexport", newScrutariExportName);
        }
        try {
            ScrutariExportDef.checkScrutariExportName(newScrutariExportName);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.exportname", newScrutariExportName);
        }
    }

}
