/* 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.commands.AbstractPhrasesCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.overview.OverviewEngine;
import net.fichotheque.corpus.Corpus;
import net.mapeadores.util.logging.CommandMessageBuilder;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.logging.LineMessage;
import net.mapeadores.util.logging.LineLogsBuilder;
import net.mapeadores.util.request.RequestMap;


/**
 *
 * @author Vincent Calame
 */
public class ConfChangeCommand extends AbstractPhrasesCommand {

    public final static String COMMANDNAME = "ConfChange";
    public final static String COMMANDKEY = "_ CRP-35";
    public final static String CONF_PARAM = "conf";
    private Corpus corpus;
    private String conf;
    private OverviewEngine overviewEngine;

    public ConfChangeCommand(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 = overviewEngine.run(session);
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.confchange");
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        conf = getMandatory(CONF_PARAM);
        LineLogsBuilder lineLogsBuilder = new LineLogsBuilder();
        overviewEngine = new OverviewEngine(bdfServer, corpus, lineLogsBuilder);
        overviewEngine.parse(conf);
        if (lineLogsBuilder.hasMessage()) {
            CommandMessageBuilder commandMessageBuilder = CommandMessageBuilder.init();
            for (LineMessage lineMessage : lineLogsBuilder.toLineMessageList()) {
                commandMessageBuilder.addMultiError(lineMessage);
            }
            throw BdfErrors.error(commandMessageBuilder, "_ error.list.configuration");
        }
    }

}
