/* BdfServer_Commands - Copyright (c) 2010-2023 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.configuration;

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 net.fichotheque.metadata.FichothequeMetadataEditor;
import net.mapeadores.util.logging.CommandMessageBuilder;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.text.StringUtils;


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

    public final static String COMMANDNAME = "Identification";
    public final static String COMMANDKEY = "_ CNF-01";
    public final static String AUTHORITY_PARAMNAME = "authority";
    public final static String BASENAME_PARAMNAME = "basename";
    private String baseName;
    private String authority;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        boolean done;
        try (EditSession session = startEditSession(Domains.CONFIGURATION, COMMANDNAME)) {
            FichothequeMetadataEditor fichothequeMetadataEditor = session.getFichothequeEditor().getFichothequeMetadataEditor();
            boolean done1 = fichothequeMetadataEditor.setAuthority(authority);
            boolean done2 = fichothequeMetadataEditor.setBaseName(baseName);
            done = ((done1) || (done2));
        }
        if (done) {
            setDone("_ done.configuration.identification");
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        checkFichothequeAdmin();
        baseName = getMandatory(BASENAME_PARAMNAME);
        authority = getMandatory(AUTHORITY_PARAMNAME);
        CommandMessageBuilder commandMessageBuilder = CommandMessageBuilder.init();
        if (!StringUtils.isTechnicalName(baseName, true)) {
            commandMessageBuilder.addMultiError("_ error.wrong.basename_fichotheque", baseName);
        }
        if (!StringUtils.isAuthority(authority)) {
            commandMessageBuilder.addMultiError("_ error.wrong.authority", authority);
        }
        if (commandMessageBuilder.hasMultiError()) {
            throw BdfErrors.error(commandMessageBuilder, "_ error.list.configuration");
        }
    }

}
