/* BdfServer_Commands - Copyright (c) 2021-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 static fr.exemole.bdfserver.api.instruction.BdfInstructionConstants.CORPUS_OBJ;
import fr.exemole.bdfserver.api.interaction.Domains;
import fr.exemole.bdfserver.api.ui.IncludeUi;
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.IncludeUiBuilder;
import net.fichotheque.FichothequeConstants;
import net.fichotheque.corpus.Corpus;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "SpecialIncludeAdd";
    public final static String COMMANDKEY = "_ CRP-31";
    public final static String NAME_PARAMNAME = "name";
    private Corpus corpus;
    private String name;

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

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

    @Override
    protected void doCommand() {
        UiComponents uiComponents = bdfServer.getUiManager().getMainUiComponents(corpus);
        boolean done;
        try (EditSession session = startEditSession(Domains.CORPUS, COMMANDNAME)) {
            done = session.getBdfServerEditor().putComponentUi(uiComponents, buildIncludeUi());
        }
        putResultObject(CORPUS_OBJ, corpus);
        if (done) {
            setDone("_ done.corpus.subsetincludecreation", name);
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        corpus = requestHandler.getMandatoryCorpus();
        checkSubsetAdmin(corpus);
        name = getMandatory(NAME_PARAMNAME);
        if (!testName(name)) {
            throw BdfErrors.unknownParameterValue(NAME_PARAMNAME, name);
        }
    }

    private boolean testName(String name) {
        switch (name) {
            case FichothequeConstants.LIAGE_NAME:
            case FichothequeConstants.PARENTAGE_NAME:
                return true;
            default:
                return false;
        }
    }

    private IncludeUi buildIncludeUi() {
        IncludeUiBuilder includeUiBuilder = IncludeUiBuilder.initSpecial(name);
        return includeUiBuilder.toIncludeUi();
    }

}
