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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.instruction.AbstractBdfCommand;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import fr.exemole.bdfserver.tools.users.BdfUserUtils;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


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

    public final static String COMMANDNAME = "UserStore";
    public final static String NAME_PARAMNAME = "name";
    public final static String KEY_PARAMNAME = "key";
    public final static String VALUE_PARAMNAME = "value";
    private String name;
    private String key;
    private String value;

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

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

    @Override
    protected void doCommand() throws ErrorMessageException {
        synchronized (bdfUser.getRedacteur()) {
            bdfServer.store(bdfUser, name, key, value);
        }
    }

    @Override
    protected void checkParameters() throws ErrorMessageException {
        name = getMandatory(NAME_PARAMNAME);
        if (!BdfUserUtils.isValidStoreName(name)) {
            throw BdfErrors.wrongParameterValue(NAME_PARAMNAME, name);
        }
        key = getMandatory(KEY_PARAMNAME);
        if (!BdfUserUtils.isValidStoreKey(key)) {
            throw BdfErrors.wrongParameterValue(KEY_PARAMNAME, key);
        }
        value = requestHandler.getTrimedParameter(VALUE_PARAMNAME);
        if (value.isEmpty()) {
            value = null;
        }
    }

}
