/* BdfServer_Commands - Copyright (c) 2024-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.api.interaction.InteractionConstants;
import fr.exemole.bdfserver.tools.externalsource.ExternalSourceUtils;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import net.fichotheque.externalsource.ExternalSource;
import net.fichotheque.thesaurus.Motcle;
import net.fichotheque.thesaurus.Thesaurus;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "MotcleCheck";
    private Thesaurus thesaurus;
    private Motcle motcle;
    private ExternalSource externalSource;
    private int newId;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        if (motcle == null) {
            try (EditSession session = startEditSession(Domains.THESAURUS, COMMANDNAME)) {
                motcle = externalSource.getMotcle(session.getFichothequeEditor(), thesaurus, newId);
            }
            if (motcle == null) {
                throw BdfErrors.unknownParameterValue(InteractionConstants.ID_PARAMNAME, String.valueOf(newId));
            }
        }
        putResultObject(THESAURUS_OBJ, thesaurus);
        putResultObject(MOTCLE_OBJ, motcle);
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        thesaurus = requestHandler.getMandatoryThesaurus();
        checkSubsetAccess(thesaurus);
        externalSource = ExternalSourceUtils.getExternalSource(bdfServer, thesaurus);
        if ((externalSource == null) || (externalSource.isIdalphaBased())) {
            motcle = requestHandler.getMandatoryMotcle();
            return;
        }
        try {
            motcle = requestHandler.getMandatoryMotcle();
        } catch (ErrorMessageException eme) {
            newId = requestHandler.getMandatoryId();
            motcle = null;
        }
    }


}
