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

import fr.exemole.bdfserver.multi.api.Multi;
import fr.exemole.bdfserver.multi.api.central.CentralUserEditor;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.text.ParseException;
import net.fichotheque.utils.SphereUtils;
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;
import net.mapeadores.util.request.RequestMap;
import net.mapeadores.util.security.PasswordChecker;
import net.mapeadores.util.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public class CentralUserCreationCommand extends AbstractCentralMultiCommand {

    public final static String COMMAND_NAME = "CentralUserCreation";
    public final static String NEWLOGIN_PARAMNAME = "newlogin";
    public final static String SURNAME_PARAMNAME = "surname";
    public final static String NONLATIN_PARAMNAME = "nonlatin";
    public final static String FORENAME_PARAMNAME = "forename";
    public final static String SURNAMEFIRST_PARAMNAME = "surnamefirst";
    public final static String EMAIL_PARAMNAME = "email";
    public final static String PASSWORD1_PARAMNAME = "password1";
    public final static String PASSWORD2_PARAMNAME = "password2";

    public CentralUserCreationCommand(Multi multi, RequestMap requestMap) {
        super(multi, requestMap);
    }

    @Override
    public CommandMessage doCommand() throws ErrorMessageException {
        initCentralSphere();
        String newlogin = getLogin();
        PersonCore person = getPerson();
        EmailCore email = getEmail();
        String password = getPassword();
        String encryptedPassword = PasswordChecker.getHash(PasswordChecker.PBKDF2, password);
        initCentralEditors();
        synchronized (getCentralSphere()) {
            CentralUserEditor centralUserEditor = centralSphereEditor.createCentralUser(newlogin);
            centralUserEditor.setPerson(person);
            centralUserEditor.setEmail(email);
            centralUserEditor.setEncryptedPassword(encryptedPassword);
            centralUserEditor.setLangContext(multi.getMultiMetadata().getWorkingLangs().get(0), null, null);
            saveChanges();
        }
        return done("_ done.sphere.redacteurcreation", newlogin);
    }

    private String getLogin() throws ErrorMessageException {
        String newlogin = getMandatory(NEWLOGIN_PARAMNAME);
        newlogin = newlogin.trim();
        if (newlogin.length() == 0) {
            throw BdfErrors.error("_ error.empty.login", newlogin);
        }
        if (!SphereUtils.testLogin(newlogin)) {
            throw BdfErrors.error("_ error.wrong.login", newlogin);
        }
        if (centralSphere.hasCentralUser(newlogin)) {
            throw BdfErrors.error("_ error.existing.login", newlogin);
        }
        return newlogin;
    }

    private PersonCore getPerson() throws ErrorMessageException {
        String surname = getMandatory(SURNAME_PARAMNAME);
        surname = StringUtils.cleanString(surname);
        String forename = StringUtils.cleanString(requestMap.getParameter(FORENAME_PARAMNAME));
        if (forename == null) {
            forename = "";
        }
        String nonlatin = StringUtils.cleanString(requestMap.getParameter(NONLATIN_PARAMNAME));
        if (nonlatin == null) {
            nonlatin = "";
        }
        boolean surnameFirst = requestMap.isTrue(SURNAMEFIRST_PARAMNAME);
        return PersonCoreUtils.toPersonCore(surname, forename, nonlatin, surnameFirst);
    }

    private EmailCore getEmail() throws ErrorMessageException {
        String email = StringUtils.cleanString(requestMap.getParameter(EMAIL_PARAMNAME));
        if ((email == null) || (email.length() == 0)) {
            return null;
        } else {
            try {
                return EmailCoreUtils.parse(email);
            } catch (ParseException pe) {
                throw BdfErrors.error("_ error.wrong.email", email);
            }
        }
    }

    private String getPassword() throws ErrorMessageException {
        String mdp1 = getMandatory(PASSWORD1_PARAMNAME);
        String mdp2 = getMandatory(PASSWORD2_PARAMNAME);
        if (!mdp1.equals(mdp2)) {
            throw BdfErrors.error("_ error.wrong.password_different");
        }
        String password = mdp1;
        if (password.length() == 0) {
            throw BdfErrors.error("_ error.empty.password");
        }
        if (password.length() < 4) {
            throw BdfErrors.error("_ error.wrong.password_tooshort");
        }
        return password;
    }

}
