# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/routes/appstudio.ipynb.

# %% auto 0
__all__ = ['AppStudioRetrieval_byId_Error', 'AppStudioAccessRetrieval_Error', 'AppStudioAdminSummary_Error',
           'AppStudioSharing_Error', 'get_apstudio_by_id', 'get_appstudio_access', 'get_appstudios_adminsummary',
           'generate_body_add_page_owner_appstudios', 'generate_body_share_appstudio', 'add_page_owner', 'share']

# %% ../../nbs/routes/appstudio.ipynb 2
import httpx
from typing import List
import domolibrary.client.get_data as gd
import domolibrary.client.ResponseGetData as rgd
import domolibrary.client.DomoAuth as dmda
import domolibrary.client.DomoError as dmde

# %% ../../nbs/routes/appstudio.ipynb 6
class AppStudioRetrieval_byId_Error(dmde.DomoError):
    def __init__(
        self,
        status,
        domo_instance,
        appstudio_id,
        response,
        function_name=None,
        parent_class=None,
    ):
        super().__init__(
            status=status,
            function_name=function_name,
            parent_class=parent_class,
            message=f"failed to retrieve appstudio_id: {appstudio_id}",
            domo_instance=domo_instance,
        )
        
        
class AppStudioAccessRetrieval_Error(dmde.DomoError):
    def __init__(
        self,
        status,
        domo_instance,
        appstudio_id,
        response,
        function_name=None,
        parent_class=None,
    ):
        super().__init__(
            status=status,
            function_name=function_name,
            parent_class=parent_class,
            message=f"failed to retrieve access list for appstudio_id: {appstudio_id}",
            domo_instance=domo_instance,
        )
        
class AppStudioAdminSummary_Error(dmde.DomoError):
    def __init__(
        self,
        status,
        domo_instance,
        appstudio_id,
        response,
        function_name=None,
        parent_class=None,
    ):
        super().__init__(
            status=status,
            function_name=function_name,
            parent_class=parent_class,
            message=f"failed to retrieve list of appstudio from Admin Summary: {appstudio_id}",
            domo_instance=domo_instance,
        )
        
        
class AppStudioSharing_Error(dmde.DomoError):
    def __init__(
        self,
        status,
        domo_instance,
        appstudio_id,
        response,
        function_name=None,
        parent_class=None,
    ):
        super().__init__(
            status=status,
            function_name=function_name,
            parent_class=parent_class,
            message=f"failed to to share AppStudio id: {appstudio_id}",
            domo_instance=domo_instance,
        )
        

# %% ../../nbs/routes/appstudio.ipynb 9
@gd.route_function
async def get_apstudio_by_id(
    auth: dmda.DomoAuth,
    appstudio_id: str,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    debug_num_stacks_to_drop: int = 1,  # for traceback_details.  use 1 for route functions, 2 for class method
    parent_class: str = None,  # pass in self.__class__.__name__ into function
) -> (
    rgd.ResponseGetData
):  # returns ResponseGetData on success or raise Exception on error
    """retrieves a page or throws an error"""

    # 9/21/2023 - the domo UI uses /cards to get page info
    url = f"https://{auth.domo_instance}.domo.com/api/content/v1/dataapps/{appstudio_id}?authoring=true&includeHiddenViews=true"

    res = await gd.get_data(
        auth=auth,
        url=url,
        method="GET",
        debug_api=debug_api,
        session=session,
        num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
    )

    if (
        not res.is_success
        or not isinstance(res.response, dict)
        or not res.response.get("dataAppId", None)
    ):
        raise AppStudioRetrieval_byId_Error(
            status=res.status,
            appstudio_id=appstudio_id,
            function_name=res.traceback_details.function_name,
            parent_class=parent_class,
            domo_instance=auth.domo_instance,
            response=res.response,
        )

    return res

# %% ../../nbs/routes/appstudio.ipynb 13
@gd.route_function
async def get_appstudio_access(
    auth,
    appstudio_id,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    parent_class: str = None,
    debug_num_stacks_to_drop: int = 1,
):
    """retrieves accesslist, which users and groups a page is shared with"""
    url = f"https://{auth.domo_instance}.domo.com/api/content/v1/dataapps/{appstudio_id}/access"

    res = await gd.get_data(
        url,
        method="GET",
        auth=auth,
        session=session,
        debug_api=debug_api,
        num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
    )
    
    if (
        not res.is_success
    ):
        raise AppStudioAccessRetrieval_Error(
            status=res.status,
            appstudio_id=appstudio_id,
            function_name=res.traceback_details.function_name,
            parent_class=parent_class,
            domo_instance=auth.domo_instance,
            response=res.response,
        )

    return res

# %% ../../nbs/routes/appstudio.ipynb 16
async def get_appstudios_adminsummary(
    auth: dmda.DomoAuth,
    debug_loop: bool = False,
    limit=35,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    parent_class: str = None
):
    """retrieves all pages in instance user is able to see (but may not have been explicitly shared)"""

    url = f"https://{auth.domo_instance}.domo.com/api/content/v1/dataapps/adminsummary"

    offset_params = {
        "offset": "skip",
        "limit": "limit",
    }

    body = {"orderBy": "title", "ascending": True}

    def arr_fn(res):
        return res.response.get("dataAppAdminSummaries")

    res = await gd.looper(
        auth=auth,
        method="POST",
        url=url,
        arr_fn=arr_fn,
        offset_params=offset_params,
        session=session,
        loop_until_end=True,
        body=body,
        limit=limit,
        debug_loop=debug_loop,
        debug_api=debug_api,
        parent_class=parent_class
    )
    
    
    if (
        not res.is_success
    ):
        raise AppStudioAdminSummary_Error(
            status=res.status,
            appstudio_id=appstudio_id,
            function_name=res.traceback_details.function_name,
            parent_class=parent_class,
            domo_instance=auth.domo_instance,
            response=res.response,
        )
        
    return res

# %% ../../nbs/routes/appstudio.ipynb 18
def generate_body_add_page_owner_appstudios(
    appstudio_id_ls: List[int],
    group_id_ls: List[int] = None,
    user_id_ls: List[int] = None,
    note: str = "",
    send_email: bool = False,
) -> dict:
    group_id_ls = group_id_ls or []
    user_id_ls = user_id_ls or []
    owners = []
    
    for group in group_id_ls:
        owners.append({"id": group, "type": "GROUP"})
    for user in user_id_ls:
        owners.append({"id": user, "type": "USER"})

    body = {
        "entityIds": appstudio_id_ls,
        "owners": owners,
        "note": note,
        "sendEmail": send_email
    }
    
    return body


def generate_body_share_appstudio(
    resource_ids: list,
    group_ids: list = None,
    user_ids: list = None,
    message: str = None 
) -> dict:

    group_ids = group_ids or []
    user_ids = user_ids or []
    
    resource_ids = resource_ids if isinstance(resource_ids, list) else [resource_ids]
    if group_ids:
        group_ids = (
            group_ids and group_ids if isinstance(group_ids, list) else [group_ids]
        )

    if user_ids:
        user_ids = user_ids if isinstance(user_ids, list) else [user_ids]

    recipient_ls = []

    if group_ids:
        [recipient_ls.append({"type": "group", "id": str(id)}) for id in group_ids]

    if user_ids:
        [recipient_ls.append({"type": "user", "id": str(id)}) for id in user_ids]


    body = {
        "dataAppIds": resource_ids,
        "recipients": recipient_ls,
        "message": message,
    }
    
    return body

# %% ../../nbs/routes/appstudio.ipynb 19
@gd.route_function
async def add_page_owner(
    auth: dmda.DomoAuth,
    appstudio_id_ls: List[int],
    group_id_ls: List[int] = None,
    user_id_ls: List[int] = None,
    note: str = "",
    send_email: bool = False,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    parent_class: str = None,
    debug_num_stacks_to_drop=1,
) -> rgd.ResponseGetData:

    url = f"https://{auth.domo_instance}.domo.com/api/content/v1/dataapps/bulk/owners"

    
    body = generate_body_add_page_owner_appstudios( appstudio_id_ls=appstudio_id_ls,
                                                    group_id_ls=group_id_ls,
                                                    user_id_ls=user_id_ls,
                                                    note=note,
                                                    send_email=send_email)

    res = await gd.get_data(
        auth=auth,
        method="PUT",
        url=url,
        body=body,
        session=session,
        debug_api=debug_api,
        parent_class=parent_class,
        num_stacks_to_drop=debug_num_stacks_to_drop,
    )
    
    if (
        not res.is_success
    ):
        raise AppStudioSharing_Error(
            status=res.status,
            appstudio_id=appstudio_id,
            function_name=res.traceback_details.function_name,
            parent_class=parent_class,
            domo_instance=auth.domo_instance,
            response=res.response,
        )
        
    if res.is_success:
        res.response = f"{appstudio_id_ls} appstudios successfully shared with {', '.join([recipient['id'] for recipient in body['owners']])} as owners"
    return res


@gd.route_function
async def share(
    auth: dmda.DomoAuth,
    resource_ids: list,
    group_ids: list = None,
    user_ids: list = None,
    message: str = None,  # email to user
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    parent_class: str = None,
    debug_num_stacks_to_drop=1,
):

    url = f"https://{auth.domo_instance}.domo.com/api/content/v1/dataapps/share?sendEmail=false"

    
    body = generate_body_share_appstudio(
    resource_ids=resource_ids,
    group_ids=group_ids,
    user_ids=user_ids,
    message=message) 

    res = await gd.get_data(
        url,
        method="POST",
        auth=auth,
        body=body,
        session=session,
        debug_api=debug_api,
        parent_class=parent_class,
        num_stacks_to_drop=debug_num_stacks_to_drop,
    )
    if (
        not res.is_success
    ):
        raise AppStudioSharing_Error(
            status=res.status,
            appstudio_id=appstudio_id,
            function_name=res.traceback_details.function_name,
            parent_class=parent_class,
            domo_instance=auth.domo_instance,
            response=res.response,
        )

    if res.is_success:
        res.response = f"{resource_ids} appstudios successfully shared with {', '.join([recipient['id'] for recipient in body['recipients']])}"

    return res
