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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.multi.MultiUtils;
import fr.exemole.bdfserver.multi.api.Multi;
import fr.exemole.bdfserver.multi.api.MultiMetadata;
import fr.exemole.bdfserver.multi.commands.AbstractMultiCommand;
import fr.exemole.bdfserver.multi.commands.CreationParameters;
import fr.exemole.bdfserver.storage.directory.bdfdata.StartValues;
import fr.exemole.bdfserver.tools.instruction.BdfErrors;
import java.util.LinkedHashSet;
import java.util.Set;
import net.fichotheque.SubsetKey;
import net.fichotheque.utils.SphereUtils;
import net.mapeadores.util.logging.CommandMessage;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.request.RequestMap;


/**
 *
 * @author Vincent Calame
 */
public class FichothequeCreationCommand extends AbstractMultiCommand {

    public final static String COMMAND_NAME = "FichothequeCreation";
    public final static String NEWFICHOTHEQUE_PARAMNAME = "newfichotheque";
    public final static String SPHEREORIGIN_PARAMNAME = "sphereorigin";
    public final static String CENTRALSPHERE_PARAMNAME = "centralsphere";
    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";
    public final static String COPYORIGIN_PARAMNAME = "copyorigin";
    public final static String CREATION_SPHEREORIGIN_PARAMVALUE = "creation";
    public final static String CENTRAL_SPHEREORIGIN_PARAMVALUE = "central";
    public final static String COPY_SPHEREORIGIN_PARAMVALUE = "copy";


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

    @Override
    public CommandMessage doCommand() throws ErrorMessageException {
        String name = run();
        return done("_ done.multi.fichothequecreation", name);
    }

    private String run() throws ErrorMessageException {
        String name = getFichothequeName(NEWFICHOTHEQUE_PARAMNAME);
        if (multi.containsFichotheque(name)) {
            throw new ErrorMessageException("_ error.existing.fichotheque", name);
        }
        switch (getMandatory(SPHEREORIGIN_PARAMNAME)) {
            case COPY_SPHEREORIGIN_PARAMVALUE:
                runCopy(name);
                break;
            case CENTRAL_SPHEREORIGIN_PARAMVALUE:
                runCentral(name);
                break;
            default:
                runCreation(name);
                break;
        }
        return name;
    }

    private void runCreation(String name) throws ErrorMessageException {
        MultiMetadata multiMetadata = multi.getMultiMetadata();
        StartValues startValues = getStartValues(requestMap)
                .authority(multiMetadata.getAuthority())
                .basename(name)
                .workingLangs(multiMetadata.getWorkingLangs());
        multi.createFichotheque(CreationParameters.initNew(name, startValues));
    }

    private void runCopy(String name) throws ErrorMessageException {
        String copyOrigin = getMandatory(COPYORIGIN_PARAMNAME);
        if (!multi.isInit(copyOrigin)) {
            throw new ErrorMessageException("_ error.unknown.parametervalue", COPYORIGIN_PARAMNAME, copyOrigin);
        }
        BdfServer sourceBdfServer = multi.getBdfServer(copyOrigin);
        MultiMetadata multiMetadata = multi.getMultiMetadata();
        StartValues startValues = StartValues.init()
                .authority(multiMetadata.getAuthority())
                .basename(name)
                .workingLangs(multiMetadata.getWorkingLangs());
        multi.createFichotheque(CreationParameters.initNewWithSpheres(name, startValues, sourceBdfServer));
    }

    private void runCentral(String name) throws ErrorMessageException {
        String[] centralSphereArray = requestMap.getParameterValues(CENTRALSPHERE_PARAMNAME);
        if ((centralSphereArray == null) || (centralSphereArray.length == 0)) {
            throw BdfErrors.emptyMandatoryParameter(CENTRALSPHERE_PARAMNAME);
        }
        Set<String> centralSphereNameSet = multi.getCentralSphereNameSet();
        Set<String> copySet = new LinkedHashSet<String>();
        for (String centralSphere : centralSphereArray) {
            if (centralSphereNameSet.contains(centralSphere)) {
                copySet.add(centralSphere);
            }
        }
        if (copySet.isEmpty()) {
            throw BdfErrors.unknownParameterValue(CENTRALSPHERE_PARAMNAME, centralSphereArray[0]);
        }
        MultiMetadata multiMetadata = multi.getMultiMetadata();
        StartValues startValues = StartValues.init()
                .authority(multiMetadata.getAuthority())
                .basename(name)
                .workingLangs(multiMetadata.getWorkingLangs());
        for (String sphereName : copySet) {
            startValues.addCentralSphere(sphereName);
        }
        multi.createFichotheque(CreationParameters.initNewWithCentral(name, startValues));
    }


    public static StartValues getStartValues(RequestMap requestMap) throws ErrorMessageException {
        String sphereName = MultiUtils.getMandatory(requestMap, FIRSTSPHERE_PARAMNAME);
        String firstUser = MultiUtils.getMandatory(requestMap, FIRSTUSER_PARAMNAME);
        String password1 = MultiUtils.getMandatory(requestMap, FIRSTPASSWORD1_PARAMNAME);
        String password2 = MultiUtils.getMandatory(requestMap, 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);
    }

}
