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

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.album.Album;
import net.fichotheque.album.AlbumEditor;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "AlbumCreation";
    public final static String COMMANDKEY = "_ ALB-01";
    public final static String NEWALBUM_PARAMNAME = "newalbum";
    private SubsetKey newSubsetKey;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        Album album;
        try (EditSession session = startEditSession(Domains.ALBUM, COMMANDNAME)) {
            try {
                AlbumEditor albumEditor = session.getFichothequeEditor().createAlbum(newSubsetKey);
                album = albumEditor.getAlbum();
            } catch (ExistingSubsetException ese) {
                throw new ShouldNotOccurException("test done before", ese);
            }
        }
        putResultObject(ALBUM_OBJ, album);
        setDone("_ done.album.albumcreation", newSubsetKey.getKeyString());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String newAlbumName = getMandatory(NEWALBUM_PARAMNAME);
        newAlbumName = newAlbumName.trim();
        if (newAlbumName.length() == 0) {
            throw BdfErrors.error("_ error.empty.albumname");
        }
        try {
            newSubsetKey = SubsetKey.parse(SubsetKey.CATEGORY_ALBUM, newAlbumName);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.albumname", newAlbumName);
        }
        if (fichotheque.containsSubset(newSubsetKey)) {
            throw BdfErrors.error("_ error.existing.album", newAlbumName);
        }
    }

}
