/* BdfServer_Commands - Copyright (c) 2015-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.addenda;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.fichotheque.ExistingSubsetException;
import net.fichotheque.SubsetKey;
import net.fichotheque.addenda.Addenda;
import net.fichotheque.addenda.AddendaEditor;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "AddendaCreation";
    public final static String COMMANDKEY = "_ ADD-01";
    public final static String NEWADDENDA_PARAMNAME = "newaddenda";
    private SubsetKey newSubsetKey;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        Addenda addenda;
        try (EditSession session = startEditSession(Domains.ADDENDA, COMMANDNAME)) {
            try {
                AddendaEditor addendaEditor = session.getFichothequeEditor().createAddenda(newSubsetKey);
                addenda = addendaEditor.getAddenda();
            } catch (ExistingSubsetException ese) {
                throw new ShouldNotOccurException("test done before", ese);
            }
        }
        putResultObject(ADDENDA_OBJ, addenda);
        setDone("_ done.addenda.addendacreation", newSubsetKey.getKeyString());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String newAddendaName = getMandatory(NEWADDENDA_PARAMNAME);
        newAddendaName = newAddendaName.trim();
        if (newAddendaName.length() == 0) {
            throw BdfErrors.error("_ error.empty.addendaname");
        }
        try {
            newSubsetKey = SubsetKey.parse(SubsetKey.CATEGORY_ADDENDA, newAddendaName);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.addendaname", newAddendaName);
        }
        if (fichotheque.containsSubset(newSubsetKey)) {
            throw BdfErrors.error("_ error.existing.addenda", newAddendaName);
        }
    }

}
