/* 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.interaction.Domains;
import fr.exemole.bdfserver.api.managers.TableExportManager;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import net.fichotheque.EditOrigin;
import net.fichotheque.exportation.table.TableExportDescription;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;


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

    public final static String COMMANDNAME = "TableExportCopy";
    public final static String COMMANDKEY = "_ EXP-18";
    public final static String NEWTABLEEXPORT_PARAMNAME = "newtableexport";
    private String tableExportName;
    private String newTableExportName;

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

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

    @Override
    protected void doCommand() {
        EditOrigin editOrigin = bdfUser.newEditOrigin(Domains.EXPORTATION, COMMANDNAME);
        TableExportManager tableExportManager = bdfServer.getTableExportManager();
        TableExportDescription newTableExportDescription = tableExportManager.copyTableExport(tableExportName, newTableExportName, editOrigin);
        if (newTableExportDescription != null) {
            putResultObject(TABLEEXPORTDESCRIPTION_OBJ, newTableExportDescription);
            setDone("_ done.exportation.tableexportcopy", tableExportName, newTableExportName);
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        TableExportDescription tableExportDescription = requestHandler.getMandatoryTableExportDescription();
        this.tableExportName = tableExportDescription.getName();
        newTableExportName = getMandatory(NEWTABLEEXPORT_PARAMNAME).trim();
        if (newTableExportName.length() == 0) {
            throw BdfErrors.error("_ error.empty.exportname");
        }
        if (!StringUtils.isTechnicalName(newTableExportName, true)) {
            throw BdfErrors.error("_ error.wrong.exportname", newTableExportName);
        }
        if (bdfServer.getTableExportManager().containsTableExport(newTableExportName)) {
            throw BdfErrors.error("_ error.existing.tableexport", newTableExportName);
        }
    }

}
