/* BdfServer_API - Copyright (c) 2021 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.api.namespaces;

import net.fichotheque.permission.PermissionSummary;
import net.mapeadores.util.attr.Attribute;
import net.mapeadores.util.attr.AttributeKey;
import net.mapeadores.util.attr.Attributes;
import net.mapeadores.util.attr.CheckedNameSpace;


/**
 *
 * @author Vincent Calame
 */
public final class RoleSpace {

    public final static CheckedNameSpace ROLE_NAMESPACE = CheckedNameSpace.build("role");
    public final static AttributeKey READ_KEY = AttributeKey.build(ROLE_NAMESPACE, "read");
    public final static AttributeKey WRITE_KEY = AttributeKey.build(ROLE_NAMESPACE, "write");

    private RoleSpace() {

    }

    public static boolean canRead(PermissionSummary permissionSummary, Attributes attributes) {
        if (permissionSummary.isFichothequeAdmin()) {
            return true;
        }
        Attribute attribute = attributes.getAttribute(READ_KEY);
        if (attribute == null) {
            return true;
        }
        for (String value : attribute) {
            if (permissionSummary.hasRole(value)) {
                return true;
            }
        }
        return false;
    }

    public static boolean canWrite(PermissionSummary permissionSummary, Attributes attributes) {
        if (permissionSummary.isFichothequeAdmin()) {
            return true;
        }
        if (!canRead(permissionSummary, attributes)) {
            return false;
        }
        Attribute attribute = attributes.getAttribute(WRITE_KEY);
        if (attribute == null) {
            return true;
        }
        for (String value : attribute) {
            if (permissionSummary.hasRole(value)) {
                return true;
            }
        }
        return false;
    }

}
