# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/classes/50_DomoRole.ipynb.

# %% auto 0
__all__ = ['DomoRole', 'DomoRoles', 'SearchRole_NotFound']

# %% ../../nbs/classes/50_DomoRole.ipynb 2
from dataclasses import dataclass, field
import httpx

from fastcore.basics import patch_to

import domolibrary.client.DomoAuth as dmda

import domolibrary.utils.DictDot as util_dd
import domolibrary.client.DomoError as de
import domolibrary.routes.role as role_routes


# %% ../../nbs/classes/50_DomoRole.ipynb 3
@dataclass
class DomoRole:
    auth: dmda.DomoAuth = field(repr = False)

    id: str
    name: str = None
    description: str = None
    is_system_role: int = None

    grant_ls: list[str] = field(default_factory=list)
    membership_ls: list = field(default_factory=list)

    def __post_init__(self):
        self.is_system_role = 1 if self.id <= 5 else 0

    # @classmethod
    # def _from_str(cls, id, name, description=None, auth: DomoAuth = None):

    #     return cls(id=id,
    #             name=name,
    #             description=description,
    #             auth=auth
    #             )

    @classmethod
    def _from_json(cls, obj, auth=dmda.DomoAuth):

        dd = obj
        if not isinstance(dd, util_dd.DictDot):
            dd = util_dd.DictDot(obj)

        return cls(id=dd.id,
                   name=dd.name,
                   description=dd.description,
                   auth=auth
                   )


# %% ../../nbs/classes/50_DomoRole.ipynb 4
@patch_to(DomoRole)
async def get_role_grants(self: DomoRole,
                          auth: dmda.DomoAuth = None,
                          role_id: str = None,
                          debug_api: bool = False,
                          session: httpx.AsyncClient = None,
                          return_raw: bool = False
                          ):

    auth = auth or self.auth
    role_id = role_id or self.id
    res = await role_routes.get_role_grants(auth=auth,
                                            role_id=role_id,
                                            debug_api=debug_api,
                                            session=session)

    if return_raw:
        return res
        
    self.grant_ls = res.response

    return self.grant_ls


# %% ../../nbs/classes/50_DomoRole.ipynb 7
@dataclass
class DomoRoles:
    auth: dmda.DomoAuth


# %% ../../nbs/classes/50_DomoRole.ipynb 8
@patch_to(DomoRoles, cls_method=True)
async def get_roles(cls: DomoRoles,
                    auth: dmda.DomoAuth,
                    debug_api: bool = False,
                    session: httpx.AsyncClient = None,
                    return_raw: bool = False
                    ):

    res = await role_routes.get_roles(auth=auth, session=session, debug_api=debug_api)

    if return_raw:
        return res

    role_ls = res.response

    return [ DomoRole._from_json(role, auth) for role in res.response]


# %% ../../nbs/classes/50_DomoRole.ipynb 10
class SearchRole_NotFound(de.DomoError):
    def __init__(self, domo_instance,
                 role_id,
                 message='not found',
                 function_name='search_role'):

        super().__init__(domo_instance=domo_instance, message=message,
                         entity_id=role_id, function_name=function_name)

@patch_to(DomoRoles, cls_method=True)
async def search_role(cls: DomoRoles,
                    role_name: str,
                    auth: dmda.DomoAuth,
                    debug_api: bool = False,
                    session: httpx.AsyncClient = None,
                    return_raw: bool = False
                    ):

    all_roles = await DomoRoles.get_roles( auth=auth)
    
    domo_role = next(
        (role for role in all_roles if role.name == role_name), None)

    if not domo_role:
        raise SearchRole_NotFound(domo_instance=auth.domo_instance, role_id=role_name)

    return domo_role

# %% ../../nbs/classes/50_DomoRole.ipynb 17
@patch_to(DomoRoles, cls_method=True)
async def upsert_role(cls: DomoRoles,
                      auth: dmda.DomoAuth,
                      name: str,
                      description: str = None,
                      debug_api: bool = False,
                      debug_prn: bool = False,
                      session : httpx.AsyncClient=None
                      ):

    domo_role = await DomoRoles.search_role(role_name=name,
                                            auth = auth ,
                                            debug_api=debug_api,
                                            session=session,
                                            )

    if domo_role:
        return domo_role

    if debug_prn:
        print(
            f'No role match -- creating new role in {full_auth.domo_instance}')

    return await DomoRoles.create_role(auth=auth,
                                       name=name, description=description,
                                       debug_api=debug_api, session=session)

