# (c) cavaliba.com - data - role.py

# v4.0  - Wrapper around Instance(schema = role)

from app_data.data import Instance


class Role(Instance):
    CLASSNAME = "role"

    def __init__(self, iobj=None, keyname=None, classname=None, expand=False):
        super().__init__(classname=self.CLASSNAME, iobj=iobj, keyname=keyname, expand=expand)

        self.users = None
        self.groups = None
        self.permissions = None

    def __str__(self):
        return f"{self.keyname}"

    def get_users(self):
        from app_data.user import User

        if self.users is not None:
            return self.users

        seen: set[str] = set()
        self.users = []
        field = self.fields.get("users")
        if not field:
            return self.users
        for ulogin in field.value:
            if not ulogin or ulogin in seen:
                continue
            u = User.from_keyname(keyname=ulogin)
            if u and u.is_bound:
                self.users.append(u)
                seen.add(ulogin)
        return self.users

    def get_groups(self):
        from app_data.group import Group

        if self.groups is not None:
            return self.groups

        seen: set[str] = set()
        self.groups = []
        field = self.fields.get("groups")
        if not field:
            return self.groups
        for gname in field.value:
            if not gname or gname in seen:
                continue
            g = Group.from_keyname(keyname=gname)
            if g and g.is_bound:
                self.groups.append(g)
                seen.add(gname)
        return self.groups

    def get_permissions(self):
        """Return SirenePermission objects for each permission keyname in self.fields, deduplicated."""
        from app_data.permissions import permission_get_all, permission_get_by_name

        if self.permissions is not None:
            return self.permissions

        if self.keyname == "role_admin":
            self.permissions = list(permission_get_all())
            return self.permissions

        seen: set[str] = set()
        self.permissions = []

        field = self.fields.get("permissions")
        if not field:
            return self.permissions

        for pname in field.value:
            if not pname or pname in seen:
                continue
            p = permission_get_by_name(pname)
            if p:
                self.permissions.append(p)
                seen.add(pname)

        return self.permissions
