/* BdfServer_Multi - Copyright (c) 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.multi.subscribe;

import fr.exemole.bdfserver.multi.commands.AbstractMultiCommand;
import net.mapeadores.util.logging.CommandMessage;
import net.mapeadores.util.logging.ErrorMessageException;


/**
 *
 * @author Vincent Calame
 */
public abstract class SubscribeCommand extends AbstractMultiCommand {

    public final static String TOKEN_PARAMNAME = "token";
    protected final SubscribeManager subscribeManager;
    protected final SubscribeParameters subscribeParameters;

    public SubscribeCommand(SubscribeParameters subscribeParameters) {
        super(subscribeParameters.multi(), subscribeParameters.requestMap());
        this.subscribeManager = subscribeParameters.subscribeManager();
        this.subscribeParameters = subscribeParameters;
    }

    @Override
    public CommandMessage doCommand() throws ErrorMessageException {
        SubscribeResult result = doSubscribeCommand();
        return result.commandMessage();
    }

    public abstract void testCommand() throws ErrorMessageException;

    public abstract SubscribeResult doSubscribeCommand() throws ErrorMessageException;

    public static SubscribeToken getValidToken(SubscribeParameters subscribeParameters, String token) throws ErrorMessageException {
        SubscribeToken subscribeToken = subscribeParameters.subscribeManager().getSubcribeToken(token);
        if (subscribeToken == null) {
            throw new ErrorMessageException("_ error.unknown.subscribe.token", token);
        }
        if (subscribeToken.isExpired()) {
            throw new ErrorMessageException("_ error.unsupported.subscribe.token", token);
        }
        if (subscribeToken.isUsed()) {
            throw new ErrorMessageException("_ error.existing.subscribe.token", token);
        }
        return subscribeToken;
    }

}
