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

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 fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.fichotheque.ExistingIdException;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.ParentRecursivityException;
import net.fichotheque.thesaurus.Thesaurus;
import net.fichotheque.thesaurus.ThesaurusEditor;
import net.fichotheque.tools.parsers.TypoParser;
import net.fichotheque.utils.ThesaurusUtils;
import net.mapeadores.util.exceptions.ShouldNotOccurException;
import net.mapeadores.util.localisation.Lang;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.Idalpha;
import net.mapeadores.util.text.LabelChange;
import net.mapeadores.util.text.StringUtils;
import net.mapeadores.util.text.TypoOptions;


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

    public final static String COMMANDNAME = "MotcleCreation";
    public final static String COMMANDKEY = "_ THS-08";
    public final static String NEWIDALPHA_PARAMNAME = "newidalpha";
    public final static String NEWLABEL_PARAMPREFIX = "newlabel/";
    public final static String BABELIEN_NEWLANG_PARAMNAME = "babeliennewlang";
    public final static String BABELIEN_NEWLABEL_PARAMNAME = "babeliennewlabel";
    public final static String PARENT_PARAMNAME = "parent";
    private Thesaurus thesaurus;
    private String newIdalpha;
    private LabelChange motcleLabelChange;
    private Lang babelienLang;
    private String babelienNewLabel;
    private Motcle parentMotcle;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        Motcle newMotcle;
        try (EditSession session = startEditSession(Domains.THESAURUS, COMMANDNAME)) {
            ThesaurusEditor thesaurusEditor = session.getFichothequeEditor().getThesaurusEditor(thesaurus);
            try {
                newMotcle = thesaurusEditor.createMotcle(-1, newIdalpha);
            } catch (ExistingIdException | ParseException e) {
                throw new ShouldNotOccurException("test done before");
            }
            if (motcleLabelChange != null) {
                ThesaurusUtils.changeMotcleLabels(thesaurusEditor, newMotcle, motcleLabelChange);
            } else if (babelienNewLabel != null) {
                TypoOptions typoOptions = TypoOptions.getTypoOptions(babelienLang.toLocale());
                thesaurusEditor.putLabel(newMotcle, babelienLang, TypoParser.parseTypo(babelienNewLabel, typoOptions));
            }
            if (parentMotcle != null) {
                try {
                    thesaurusEditor.setParent(newMotcle, parentMotcle);
                } catch (ParentRecursivityException pre) {
                    throw new ShouldNotOccurException("child just created");
                }
            }
        }
        putResultObject(THESAURUS_OBJ, thesaurus);
        putResultObject(MOTCLE_OBJ, newMotcle);
        if (newIdalpha != null) {
            setDone("_ done.thesaurus.motclecreation_idalpha");
        } else {
            setDone("_ done.thesaurus.motclecreation_id");
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        thesaurus = requestHandler.getMandatoryThesaurus();
        checkSubsetAdmin(thesaurus);
        if (thesaurus.isIdalphaType()) {
            newIdalpha = getMandatory(NEWIDALPHA_PARAMNAME);
            newIdalpha = StringUtils.cleanString(newIdalpha);
            if (newIdalpha.length() == 0) {
                throw BdfErrors.error("_ error.empty.idalpha");
            }
            if (!Idalpha.isValid(newIdalpha)) {
                throw BdfErrors.error("_ error.wrong.idalpha", newIdalpha);
            }
            Motcle other = thesaurus.getMotcleByIdalpha(newIdalpha);
            if (other != null) {
                throw BdfErrors.error("_ error.existing.idalpha", newIdalpha);
            }
        }
        if (thesaurus.isBabelienType()) {
            babelienNewLabel = getMandatory(BABELIEN_NEWLABEL_PARAMNAME);
            String langString = getMandatory(BABELIEN_NEWLANG_PARAMNAME).trim();
            if (langString.length() > 0) {
                try {
                    babelienLang = Lang.parse(langString);
                } catch (ParseException lie) {
                    throw BdfErrors.error("_ error.wrong.lang", langString);
                }
            }
        } else {
            motcleLabelChange = requestHandler.getLabelChange(NEWLABEL_PARAMPREFIX);
        }
        this.parentMotcle = (Motcle) requestHandler.getOptionnalSubsetItem(thesaurus, PARENT_PARAMNAME);
    }

}
