/* BdfServer - Copyright (c) 2013-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.tools.roles;

import fr.exemole.bdfserver.api.roles.Permission;
import fr.exemole.bdfserver.api.roles.RoleDef;
import java.text.ParseException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import net.fichotheque.SubsetKey;
import net.mapeadores.util.attr.Attributes;
import net.mapeadores.util.misc.DefBuilder;
import net.mapeadores.util.text.Labels;


/**
 *
 * @author Vincent Calame
 */
public class RoleDefBuilder extends DefBuilder {

    private final String name;
    private final Map<SubsetKey, Permission> subsetPermissionMap = new LinkedHashMap<SubsetKey, Permission>();

    public RoleDefBuilder(String name) {
        try {
            RoleDef.checkRoleName(name);
        } catch (ParseException pe) {
            throw new IllegalArgumentException("Not a valid role name: " + name);
        }
        this.name = name;
    }

    public void putSubsetPermission(SubsetKey subsetKey, Permission permission) {
        subsetPermissionMap.put(subsetKey, permission);
    }

    public RoleDef toRoleDef() {
        int size = subsetPermissionMap.size();
        int p = 0;
        RoleDef.SubsetEntry[] subsetEntryArray = new RoleDef.SubsetEntry[size];
        for (Map.Entry<SubsetKey, Permission> entry : subsetPermissionMap.entrySet()) {
            subsetEntryArray[p] = RoleUtils.toSubsetEntry(entry.getKey(), entry.getValue());
            p++;
        }
        Labels titleLabels = toLabels();
        Attributes attributes = toAttributes();
        return new InternalRoleDef(name, RoleUtils.wrap(subsetEntryArray), titleLabels, attributes);
    }

    public static RoleDefBuilder init(String roleName) {
        return new RoleDefBuilder(roleName);
    }


    private static class InternalRoleDef implements RoleDef {

        private final String name;
        private final List<SubsetEntry> subsetEntryList;
        private final Labels titleLabels;
        private final Attributes attributes;

        private InternalRoleDef(String name, List<SubsetEntry> subsetEntryList,
                Labels titleLabels, Attributes attributes) {
            this.name = name;
            this.subsetEntryList = subsetEntryList;
            this.titleLabels = titleLabels;
            this.attributes = attributes;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public Labels getTitleLabels() {
            return titleLabels;
        }

        @Override
        public Attributes getAttributes() {
            return attributes;
        }

        @Override
        public List<SubsetEntry> getSubsetEntryList() {
            return subsetEntryList;
        }

    }

}
