# (c) cavaliba.com - tests / helper_iam

from app_data.group import Group
from app_data.loader import load_broker
from app_data.role import Role
from app_data.user import User
from app_user.models import SirenePermission

_AAA = {"username": "unittest:helper"}


def add_admin_user(login="adminuser"):
    user = User(keyname=login)
    user.displayname = login
    user.save(aaa=_AAA, action="create")
    datalist = [
        {"classname": "role", "_action": "update", "keyname": "role_admin", "users": [login]}
    ]
    load_broker(datalist=datalist, aaa={"perms": ["p_role_update"]})
    return user


def add_user_with_perm(login="unittest", perms=[]):
    user = User(keyname=login)
    user.displayname = login
    user.save(aaa=_AAA, action="create")
    for perm_name in perms:
        SirenePermission.objects.get_or_create(keyname=perm_name)
    role_keyname = f"role_{login}"
    datalist = [
        {
            "classname": "role",
            "_action": "create",
            "keyname": role_keyname,
            "displayname": role_keyname,
            "users": [login],
            "permissions": perms,
        }
    ]
    load_broker(datalist=datalist, aaa={"perms": ["p_role_create"]})


def add_user(login="testuser01", displayname=None, is_enabled=True):
    user = User(keyname=login)
    user.displayname = displayname or login
    user.is_enabled = is_enabled
    user.save(aaa=_AAA, action="create")
    return user


def add_group(name="testgroup01", displayname=None):
    g = Group(keyname=name)
    g.displayname = displayname or name
    g.save(aaa=_AAA, action="create")
    return g


def add_role(name="testrole01", displayname=None):
    r = Role(keyname=name)
    r.displayname = displayname or name
    r.save(aaa=_AAA, action="create")
    return r
