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

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.api.EditSession;
import fr.exemole.bdfserver.api.managers.PermissionManager;
import fr.exemole.bdfserver.multi.api.Multi;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.fichotheque.FichothequeConstants;
import net.fichotheque.sphere.Redacteur;
import net.fichotheque.sphere.Sphere;
import net.fichotheque.sphere.SphereEditor;
import net.mapeadores.util.logging.CommandMessage;
import net.mapeadores.util.logging.ErrorMessageException;
import net.mapeadores.util.logging.LogUtils;
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.text.StringUtils;


/**
 *
 * @author Vincent Calame
 */
public class PersonChangeCommand extends AbstractPersonMultiCommand {

    public final static String COMMAND_NAME = "PersonChange";
    public final static String TYPE_PARAMNAME = "type";
    public final static String NAME_TYPE_PARAMVALUE = "name";
    public final static String EMAIL_TYPE_PARAMVALUE = "email";
    public final static String STATUS_TYPE_PARAMVALUE = "status";
    public final static String NEWPASSWORD_TYPE_PARAMVALUE = "newpassword";
    public final static String COPY_PASSWORD_TYPE_PARAMVALUE = "copy_password";
    public final static String COPY_ALL_TYPE_PARAMVALUE = "copy_all";
    public final static String TARGET_PARAMNAME = "target";
    public final static String EMAIL_PARAMNAME = "email";
    public final static String SURNAME_PARAMNAME = "surname";
    public final static String FICHOTHEQUES_PARAMNAME = "fichotheques";
    public final static String FORENAME_PARAMNAME = "forename";
    public final static String NONLATIN_PARAMNAME = "nonlatin";
    public final static String PASSWORD1_PARAMNAME = "password1";
    public final static String PASSWORD2_PARAMNAME = "password2";
    public final static String STATUS_PARAMNAME = "status";
    public final static String SURNAMEFIRST_PARAMNAME = "surnamefirst";
    public final static String ALL_PARAMVALUE = "all";
    public final static String SELECTION_PARAMVALUE = "selection";
    public final static String ADMIN_STATUS_PARAMVALUE = "admin";
    public final static String USER_STATUS_PARAMVALUE = "user";
    public final static String READONLY_STATUS_PARAMVALUE = "readonly";
    public final static String INACTIVE_STATUS_PARAMVALUE = "inactive";

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

    @Override
    public CommandMessage doCommand() throws ErrorMessageException {
        initPersonParameters();
        String type = getMandatory(TYPE_PARAMNAME);
        switch (type) {
            case NAME_TYPE_PARAMVALUE:
                return runNameChange();
            case EMAIL_TYPE_PARAMVALUE:
                return runEmailChange();
            case STATUS_TYPE_PARAMVALUE:
                return runStatusChange();
            case NEWPASSWORD_TYPE_PARAMVALUE:
                return runNewPasswordChange();
            case COPY_PASSWORD_TYPE_PARAMVALUE:
                return runCopyPasswordChange();
            case COPY_ALL_TYPE_PARAMVALUE:
                return runCopyAllChange();
            default:
                throw new ErrorMessageException("_ error.unknown.parametervalue", TYPE_PARAMNAME, type);
        }
    }

    private CommandMessage runNameChange() throws ErrorMessageException {
        String surname = StringUtils.cleanString(requestMap.getParameter(SURNAME_PARAMNAME));
        if (surname == null) {
            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 = false;
        String surnameFirstValue = requestMap.getParameter(SURNAMEFIRST_PARAMNAME);
        if (surnameFirstValue != null) {
            switch (surnameFirstValue.toLowerCase()) {
                case "1":
                case "true":
                    surnameFirst = true;
                    break;
            }
        }
        PersonCore personCore = PersonCoreUtils.toPersonCore(surname, forename, nonlatin, surnameFirst);
        for (Info info : getInfoList()) {
            BdfServer bdfServer = info.getBdfServer();
            synchronized (bdfServer) {
                try (EditSession editSession = initEditSession(bdfServer)) {
                    SphereEditor sphereEditor = editSession.getFichothequeEditor().getSphereEditor(sphereKey);
                    sphereEditor.setPerson(info.getRedacteur(), personCore);
                }
            }
        }
        return done("_ done.multi.personchange");
    }

    private CommandMessage runEmailChange() throws ErrorMessageException {
        String email = StringUtils.cleanString(getMandatory(EMAIL_PARAMNAME, true));
        try {
            EmailCore emailCore;
            if (email.isEmpty()) {
                emailCore = null;
            } else {
                emailCore = EmailCoreUtils.parse(email);
            }
            for (Info info : getInfoList()) {
                BdfServer bdfServer = info.getBdfServer();
                synchronized (bdfServer) {
                    try (EditSession editSession = initEditSession(bdfServer)) {
                        SphereEditor sphereEditor = editSession.getFichothequeEditor().getSphereEditor(sphereKey);
                        sphereEditor.setEmail(info.getRedacteur(), emailCore);
                    }
                }
            }
            return done("_ done.multi.personchange");
        } catch (ParseException pe) {
            throw new ErrorMessageException("_ error.wrong.parametervalue", EMAIL_PARAMNAME, email);
        }
    }

    private CommandMessage runNewPasswordChange() throws ErrorMessageException {
        String mdp1 = getMandatory(PASSWORD1_PARAMNAME, true);
        String mdp2 = getMandatory(PASSWORD2_PARAMNAME, true);
        if (!mdp1.equals(mdp2)) {
            throw new ErrorMessageException("_ error.wrong.password_different");
        }
        if (mdp1.isEmpty()) {
            throw new ErrorMessageException("_ error.empty.password");
        }
        if (mdp1.length() < 4) {
            throw new ErrorMessageException("_ error.wrong.password_tooshort");
        }
        for (Info info : getInfoList()) {
            info.getBdfServer().getPasswordManager().setPassword(info.getRedacteur().getGlobalId(), mdp1);
        }
        return LogUtils.done("_ done.multi.personchange");
    }

    private CommandMessage runCopyPasswordChange() throws ErrorMessageException {
        CopyOrigin copyOrigin = getCopyOrigin();
        List<Info> infoList = getInfoList();
        copyPassword(copyOrigin, infoList, true);
        return done("_ done.multi.personchange");
    }

    private CommandMessage runCopyAllChange() throws ErrorMessageException {
        CopyOrigin copyOrigin = getCopyOrigin();
        Redacteur originRedacteur = copyOrigin.getRedacteur();
        List<Info> infoList = getInfoList();
        copyPassword(copyOrigin, infoList, false);
        for (Info info : getInfoList()) {
            BdfServer bdfServer = info.getBdfServer();
            synchronized (bdfServer) {
                try (EditSession editSession = initEditSession(bdfServer)) {
                    SphereEditor sphereEditor = editSession.getFichothequeEditor().getSphereEditor(sphereKey);
                    sphereEditor.setPerson(info.getRedacteur(), originRedacteur.getPersonCore());
                    sphereEditor.setEmail(info.getRedacteur(), originRedacteur.getEmailCore());
                }
            }
        }
        return done("_ done.multi.personchange");
    }


    private void copyPassword(CopyOrigin copyOrigin, List<Info> infoList, boolean errorIfEmpty) throws ErrorMessageException {
        String encryptedPassword = copyOrigin.getEncryptedPassword();
        if ((encryptedPassword == null) && (errorIfEmpty)) {
            throw new ErrorMessageException("_ error.empty.password");
        }
        for (Info info : infoList) {
            BdfServer bdfServer = info.getBdfServer();
            if (!bdfServer.getName().equals(copyOrigin.getOriginName())) {
                bdfServer.getPasswordManager().setEncryptedPassword(info.getRedacteur().getGlobalId(), encryptedPassword);
            }
        }
    }


    private CommandMessage runStatusChange() throws ErrorMessageException {
        String status = getMandatory(STATUS_PARAMNAME);
        List<Info> infoList = getInfoList();
        if (!status.equals(ADMIN_STATUS_PARAMVALUE)) {
            checkUniqueAdmin(infoList);
        }
        switch (status) {
            case ADMIN_STATUS_PARAMVALUE:
                runAdminChange(infoList, true);
                break;
            case USER_STATUS_PARAMVALUE:
                runAdminChange(infoList, false);
                break;
            case READONLY_STATUS_PARAMVALUE:
                runStatusChange(infoList, FichothequeConstants.READONLY_STATUS);
                break;
            case INACTIVE_STATUS_PARAMVALUE:
                runStatusChange(infoList, FichothequeConstants.INACTIVE_STATUS);

        }
        return done("_ done.multi.personchange");
    }

    private void runAdminChange(List<Info> infoList, boolean isAdmin) {
        for (Info info : infoList) {
            BdfServer bdfServer = info.getBdfServer();
            Redacteur redacteur = info.getRedacteur();
            boolean isCurrentAdmin = bdfServer.getPermissionManager().isAdmin(redacteur);
            synchronized (bdfServer) {
                try (EditSession editSession = initEditSession(bdfServer)) {
                    if (!redacteur.getStatus().equals(FichothequeConstants.ACTIVE_STATUS)) {
                        SphereEditor sphereEditor = editSession.getFichothequeEditor().getSphereEditor(sphereKey);
                        sphereEditor.setStatus(redacteur, FichothequeConstants.ACTIVE_STATUS);
                    }
                    if (isCurrentAdmin != isAdmin) {
                        editSession.getBdfServerEditor().setAdmin(redacteur.getGlobalId(), isAdmin);
                    }
                }
            }
        }
    }

    private void runStatusChange(List<Info> infoList, String status) {
        for (Info info : infoList) {
            BdfServer bdfServer = info.getBdfServer();
            Redacteur redacteur = info.getRedacteur();
            String currentStatus = redacteur.getStatus();
            if (!status.equals(currentStatus)) {
                synchronized (bdfServer) {
                    try (EditSession editSession = initEditSession(bdfServer)) {
                        if (bdfServer.getPermissionManager().isAdmin(redacteur)) {
                            editSession.getBdfServerEditor().setAdmin(redacteur.getGlobalId(), false);
                        }
                        SphereEditor sphereEditor = editSession.getFichothequeEditor().getSphereEditor(sphereKey);
                        sphereEditor.setStatus(redacteur, status);
                    }
                }
            }
        }
    }

    private EditSession initEditSession(BdfServer bdfServer) {
        return bdfServer.initEditSession("_admin", "PersonChange");
    }

    private void checkUniqueAdmin(List<Info> infoList) throws ErrorMessageException {
        for (Info info : infoList) {
            PermissionManager permissionManager = info.getBdfServer().getPermissionManager();
            if ((permissionManager.isAdmin(info.getRedacteur()) && (permissionManager.getAdminRedacteurList().size() < 2))) {
                throw new ErrorMessageException("_ error.unsupported.lastadmin_fichotheque", info.getBdfServer().getName());
            }
        }
    }

    private List<Info> getInfoList() {
        List<Info> result = new ArrayList<Info>();
        String targetValue = requestMap.getParameter(TARGET_PARAMNAME);
        Set<String> nameSet;
        if ((targetValue != null) && (targetValue.equals(SELECTION_PARAMVALUE))) {
            String[] fichotheques = requestMap.getParameterValues(FICHOTHEQUES_PARAMNAME);
            nameSet = new HashSet<String>();
            if (fichotheques != null) {
                for (String fichothequeName : fichotheques) {
                    nameSet.add(fichothequeName);
                }
            }
        } else {
            nameSet = null;
        }
        for (String name : multi.getExistingNameSet()) {
            if (multi.isInit(name)) {
                if ((nameSet == null) || (nameSet.contains(name))) {
                    try {
                        BdfServer bdfServer = multi.getBdfServer(name);
                        Sphere sphere = (Sphere) bdfServer.getFichotheque().getSubset(sphereKey);
                        if (sphere != null) {
                            Redacteur redacteur = sphere.getRedacteurByLogin(login);
                            if (redacteur != null) {
                                result.add(new Info(bdfServer, redacteur));
                            }
                        }
                    } catch (ErrorMessageException eme) {
                        return null;
                    }
                }
            }
        }
        return result;
    }


    private static class Info {

        private final BdfServer bdfServer;
        private final Redacteur redacteur;

        private Info(BdfServer bdfServer, Redacteur redacteur) {
            this.bdfServer = bdfServer;
            this.redacteur = redacteur;
        }

        private BdfServer getBdfServer() {
            return bdfServer;
        }

        private Redacteur getRedacteur() {
            return redacteur;
        }

    }

}
