/* BdfServer_Commands - Copyright (c) 2011-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.CommentUi;
import fr.exemole.bdfserver.api.ui.UiComponents;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.ui.components.CommentUiBuilder;
import net.fichotheque.corpus.Corpus;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "CommentCreation";
    public final static String COMMANDKEY = "_ CRP-15";
    private Corpus corpus;
    private int location;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        UiComponents uiComponents = bdfServer.getUiManager().getMainUiComponents(corpus);
        String name = getCommentName(uiComponents);
        boolean done;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            CommentUiBuilder commentUiBuilder = CommentUiBuilder.init(bdfServer.getUiManager().getHtmlCleaner(), name)
                    .setLocation(location);
            CommentChangeCommand.putHtmlString(commentUiBuilder, requestHandler, CommentChangeCommand.COMMENT_PREFIX);
            done = session.getBdfServerEditor().putComponentUi(uiComponents, commentUiBuilder.toCommentUi());
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.commentcreation", name);
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        location = CommentChangeCommand.getLocation(requestHandler, CommentChangeCommand.LOCATION_PARAMNAME);
    }

    private String getCommentName(UiComponents uiComponents) {
        int number = 1;
        String name = null;
        while (true) {
            name = "c" + String.valueOf(number);
            if (!uiComponents.contains(CommentUi.toComponentName(name))) {
                break;
            } else {
                number++;
            }
        }
        return name;
    }

}
