/* 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.api.BdfServer;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.multi.api.MultiMetadata;
import fr.exemole.bdfserver.multi.commands.CreationParameters;
import fr.exemole.bdfserver.storage.directory.bdfdata.StartValues;
import net.fichotheque.SubsetKey;
import net.fichotheque.sphere.Redacteur;
import net.fichotheque.sphere.Sphere;
import net.fichotheque.sphere.SphereEditor;
import net.fichotheque.utils.SphereUtils;
import net.mapeadores.util.logging.ErrorMessageException;


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

    public final static String COMMAND_NAME = "FichothequeSubscribe";
    public final static String TOKEN_PARAMNAME = "token";
    public final static String NEWFICHOTHEQUE_PARAMNAME = "newfichotheque";
    public final static String FIRSTSPHERE_PARAMNAME = "firstsphere";
    public final static String FIRSTUSER_PARAMNAME = "firstuser";
    public final static String FIRSTPASSWORD1_PARAMNAME = "firstpassword_1";
    public final static String FIRSTPASSWORD2_PARAMNAME = "firstpassword_2";
    private String fichothequeName;
    private StartValues startValues;
    private SubscribeToken subscribeToken;

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

    @Override
    public SubscribeResult doSubscribeCommand() throws ErrorMessageException {
        testCommand();
        multi.createFichotheque(CreationParameters.initNew(fichothequeName, startValues));
        subscribeToken.setUsed(true);
        populateFichotheque(multi.getBdfServer(fichothequeName), startValues, subscribeToken);
        return SubscribeResult.init(subscribeParameters).fichothequeName(fichothequeName).login(startValues.firstuser());
    }

    @Override
    public void testCommand() throws ErrorMessageException {
        MultiMetadata multiMetadata = multi.getMultiMetadata();
        String token = getMandatory(SubscribeCommand.TOKEN_PARAMNAME);
        subscribeToken = SubscribeCommand.getValidToken(subscribeParameters, token);
        fichothequeName = getFichothequeName(NEWFICHOTHEQUE_PARAMNAME);
        if (multi.containsFichotheque(fichothequeName)) {
            throw new ErrorMessageException("_ error.existing.fichotheque", fichothequeName);
        }
        startValues = getStartValues()
                .authority(multiMetadata.getAuthority())
                .basename(fichothequeName)
                .workingLangs(multiMetadata.getWorkingLangs());
    }

    private StartValues getStartValues() throws ErrorMessageException {
        String sphereName = getMandatory(FIRSTSPHERE_PARAMNAME);
        String firstUser = getMandatory(FIRSTUSER_PARAMNAME);
        String password1 = getMandatory(FIRSTPASSWORD1_PARAMNAME);
        String password2 = getMandatory(FIRSTPASSWORD2_PARAMNAME);
        SubsetKey sphereKey;
        try {
            sphereKey = SubsetKey.parse(SubsetKey.CATEGORY_SPHERE, sphereName);
        } catch (java.text.ParseException pe) {
            throw new ErrorMessageException("_ error.wrong.spherename", sphereName);
        }
        if (!SphereUtils.testLogin(firstUser)) {
            throw new ErrorMessageException("_ error.wrong.login", firstUser);
        }
        if (!password1.equals(password2)) {
            throw new ErrorMessageException("_ error.wrong.password_different");
        }
        return StartValues.init()
                .spherename(sphereKey.getSubsetName())
                .firstuser(firstUser)
                .firstpassword(password1);
    }

    private void populateFichotheque(BdfServer bdfServer, StartValues startValues, SubscribeToken subscribeToken) {
        SubsetKey sphereKey = SubsetKey.build(SubsetKey.CATEGORY_SPHERE, startValues.spherename());
        String login = startValues.firstuser();
        Redacteur redacteur = ((Sphere) bdfServer.getFichotheque().getSubset(sphereKey)).getRedacteurByLogin(login);
        try (EditSession editSession = bdfServer.initEditSession("_admin", "FichothequeSubscribe")) {
            SphereEditor sphereEditor = editSession.getFichothequeEditor().getSphereEditor(sphereKey);
            sphereEditor.setPerson(redacteur, subscribeToken.getPerson());
            sphereEditor.setEmail(redacteur, subscribeToken.getEmail());

        }
    }

}
