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

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 net.fichotheque.ExistingSubsetException;
import net.fichotheque.SubsetKey;
import net.fichotheque.sphere.Sphere;
import net.fichotheque.sphere.SphereEditor;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "SphereCreation";
    public final static String COMMANDKEY = "_ SPH-01";
    public final static String NEWSPHERE_PARAMNAME = "newsphere";
    private SubsetKey sphereKey;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        Sphere sphere;
        try (EditSession session = startEditSession(Domains.SPHERE, COMMANDNAME)) {
            try {
                SphereEditor sphereEditor = session.getFichothequeEditor().createSphere(sphereKey);
                sphere = sphereEditor.getSphere();
            } catch (ExistingSubsetException ese) {
                throw new ShouldNotOccurException("test before ExistingSubsetException");
            }
        }
        putResultObject(SPHERE_OBJ, sphere);
        setDone("_ done.sphere.spherecreation", sphereKey.getKeyString());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String nameParam = getMandatory(NEWSPHERE_PARAMNAME);
        nameParam = nameParam.trim();
        if (nameParam.length() == 0) {
            throw BdfErrors.error("_ error.empty.spherename");
        }
        try {
            sphereKey = SubsetKey.parse(SubsetKey.CATEGORY_SPHERE, nameParam);
        } catch (java.text.ParseException pe) {
            throw BdfErrors.error("_ error.wrong.spherename", nameParam);
        }
        if (fichotheque.containsSubset(sphereKey)) {
            throw BdfErrors.error("_ error.existing.sphere", nameParam);
        }
    }

}
