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

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.BdfErrors;
import java.text.ParseException;
import net.fichotheque.ExistingSubsetException;
import net.fichotheque.SubsetKey;
import net.fichotheque.corpus.Corpus;
import net.fichotheque.corpus.CorpusEditor;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


/**
 *
 * @author Vincent Calame
 */
public class CorpusCreationCommand extends AbstractCorpusCreationCommand {

    public final static String COMMANDNAME = "CorpusCreation";
    public final static String COMMANDKEY = "_ CRP-01";
    public final static String NEWCORPUS_PARAMNAME = "newcorpus";
    private SubsetKey newCorpusKey;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        Corpus newCorpus;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            try {
                CorpusEditor corpusEditor = session.getFichothequeEditor().createCorpus(newCorpusKey, masterSubset);
                newCorpus = corpusEditor.getCorpus();
            } catch (ExistingSubsetException ese) {
                throw new ShouldNotOccurException("test before ExistingSubsetException");
            }
        }
        putResultObject(CORPUS_OBJ, newCorpus);
        setDone("_ done.corpus.corpuscreation", newCorpusKey.getKeyString());
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        String newCorpusName = getMandatory(NEWCORPUS_PARAMNAME);
        initSubsetMaster();
        newCorpusName = newCorpusName.trim();
        if (newCorpusName.length() == 0) {
            throw BdfErrors.error("_ error.empty.corpusname");
        }
        try {
            newCorpusKey = SubsetKey.parse(SubsetKey.CATEGORY_CORPUS, newCorpusName);
            if (fichotheque.containsSubset(newCorpusKey)) {
                throw BdfErrors.error("_ error.existing.corpus", newCorpusKey.getKeyString());
            }
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.corpusname", newCorpusName);
        }
    }


}
