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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.ui.DataUi;
import fr.exemole.bdfserver.api.ui.UiComponents;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.ui.components.DataUiBuilder;
import java.text.ParseException;
import net.fichotheque.corpus.Corpus;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "DataCreationCommand";
    public final static String COMMANDKEY = "_ CRP-33";
    public final static String NAME_PARAMNAME = "name";
    public final static String TYPE_PARAMNAME = "type";
    private Corpus corpus;
    private UiComponents uiComponents;
    private String name;
    private String type;

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

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

    @Override
    protected void doCommand() {
        boolean done;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            done = session.getBdfServerEditor().putComponentUi(uiComponents, DataUiBuilder.init(name, type).toDataUi());
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.datacreation", name);
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        name = getMandatory(NAME_PARAMNAME);
        type = getMandatory(TYPE_PARAMNAME);
        uiComponents = bdfServer.getUiManager().getMainUiComponents(corpus);
        String componentName = DataUi.toComponentName(name);
        if (uiComponents.contains(componentName)) {
            throw BdfErrors.error("_ error.existing.include", componentName);
        }
        try {
            DataUi.checkDataName(name);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.dataname", name);
        }
    }

}
