/* 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.SqlExportManager;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.fichotheque.exportation.sql.SqlExportDef;
import net.fichotheque.tools.exportation.sql.SqlExportDefBuilder;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "SqlExportCreation";
    public final static String COMMANDKEY = "_ EXP-41";
    public final static String NEWSQLEXPORT_PARAMNAME = "newsqlexport";
    private String newSqlExportName;

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

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

    @Override
    protected void doCommand() {
        SqlExportManager sqlExportManager = bdfServer.getSqlExportManager();
        SqlExportDef sqlExportDef = SqlExportDefBuilder.init(newSqlExportName).toSqlExportDef();
        sqlExportManager.putSqlExportDef(sqlExportDef);
        putResultObject(SQLEXPORTDEF_OBJ, sqlExportDef);
        setDone("_ done.exportation.sqlexportcreation", newSqlExportName);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        newSqlExportName = getMandatory(NEWSQLEXPORT_PARAMNAME).trim();
        if (newSqlExportName.length() == 0) {
            throw BdfErrors.error("_ error.empty.exportname");
        }
        SqlExportManager sqlExportManager = bdfServer.getSqlExportManager();
        SqlExportDef sqlExportDef = sqlExportManager.getSqlExportDef(newSqlExportName);
        if (sqlExportDef != null) {
            throw BdfErrors.error("_ error.existing.sqlexport", newSqlExportName);
        }
        try {
            SqlExportDef.checkSqlExportName(newSqlExportName);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.exportname", newSqlExportName);
        }
    }

}
