/* 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.tools.instruction.AbstractBdfCommand;
import net.fichotheque.corpus.Corpus;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;


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

    public final static String COMMANDNAME = "UiComponentPosition";
    public final static String COMMANDKEY = "_ CRP-18";
    public final static String COMPONENTPOSITION_PARAMNAME = "componentposition";
    private String componentPosition;
    private Corpus corpus;

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

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

    @Override
    protected void doCommand() {
        String[] tokens = StringUtils.getLineTokens(componentPosition, StringUtils.EMPTY_EXCLUDE);
        int count = tokens.length;
        for (int i = 0; i < count; i++) {
            tokens[i] = clean(tokens[i]);
        }
        boolean done;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            done = session.getBdfServerEditor().setPositionArray(bdfServer.getUiManager().getMainUiComponents(corpus), tokens);
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.uicomponentposition");
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        componentPosition = getMandatory(COMPONENTPOSITION_PARAMNAME);
    }

    private static String clean(String token) {
        int length = token.length();
        StringBuilder buf = new StringBuilder(length * 2);
        for (int i = 0; i < length; i++) {
            char carac = token.charAt(i);
            if ((carac == ' ') || (carac == '(')) {
                break;
            }
            buf.append(carac);
        }
        return buf.toString();
    }

}
