/* 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.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.mapeadores.util.logging.CommandMessage;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.models.EmailCore;
import net.mapeadores.util.models.EmailCoreUtils;
import net.mapeadores.util.models.PersonCore;
import net.mapeadores.util.models.PersonCoreUtils;


/**
 *
 * @author Vincent Calame
 */
public class AskForTokenCommand extends SubscribeCommand {

    public final static String COMMAND_NAME = "AskForToken";
    public final static String SURNAME_PARAMNAME = "surname";
    public final static String FORENAME_PARAMNAME = "forename";
    public final static String EMAIL_PARAMNAME = "email";
    public final static String SURNAMEFIRST_PARAMNAME = "surnamefirst";
    private PersonCore person;
    private EmailCore email;

    public AskForTokenCommand(SubscribeParameters subscribeParameters) {
        super(subscribeParameters);
    }

    @Override
    public SubscribeResult doSubscribeCommand() throws ErrorMessageException {
        testCommand();
        CommandMessage commandMessage = subscribeManager.sendToken(person, email, multi.getAdminMessageLocalisation(), subscribeParameters.rootUrl());
        return SubscribeResult.init(subscribeParameters).commandMessage(commandMessage);
    }

    @Override
    public void testCommand() throws ErrorMessageException {
        person = initPerson();
        email = initEmail(person.toStandardStyle());
    }

    private PersonCore initPerson() throws ErrorMessageException {
        String surname = getMandatory(SURNAME_PARAMNAME);
        String forename = getMandatory(FORENAME_PARAMNAME);
        boolean surnameFirst = requestMap.isTrue(SURNAMEFIRST_PARAMNAME);
        return PersonCoreUtils.toPersonCore(surname, forename, "", surnameFirst);
    }

    private EmailCore initEmail(String realName) throws ErrorMessageException {
        String emailString = getMandatory(EMAIL_PARAMNAME);
        try {
            return EmailCoreUtils.parse(emailString, realName);
        } catch (ParseException pe) {
            throw BdfErrors.error("_ error.wrong.email", emailString);
        }
    }

}
