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

# %% auto 0
__all__ = ['App_API_Exception', 'get_design_by_id', 'get_design_versions', 'Design_GET_Assets',
           'get_design_source_code_by_version', 'get_all_designs', 'get_design_permissions', 'set_design_admins',
           'add_design_admin']

# %% ../../nbs/classes/50_DomoEnterpriseApps.ipynb 2
from dataclasses import dataclass, field
import datetime as dt

from typing import List, Any
import os
import httpx
import time
import zipfile


import domolibrary.client.get_data as gd
import domolibrary.client.DomoAuth as dmda
import domolibrary.client.DomoError as de

import domolibrary.classes.DomoUser as dmdu

import domolibrary.utils.files as dmfi
import domolibrary.utils.chunk_execution as ce

from nbdev.showdoc import patch_to

# %% ../../nbs/classes/50_DomoEnterpriseApps.ipynb 6
class App_API_Exception(de.DomoError):
    def __init__(self, res, message=None):
        super().__init__(res=res, message=message)


@gd.route_function
async def get_design_by_id(
    auth: dmda.DomoAuth,
    design_id: str,
    parts="owners,cards,versions,creator",
    debug_api: bool = False,
    debug_num_stacks_to_drop = 1,
    parent_class : str = None,
    session: httpx.AsyncClient = None
):

    url = f"https://{auth.domo_instance}.domo.com/api/apps/v1/designs/{design_id}"

    res = await gd.get_data(
        url=url,
        method="get",
        params={"parts": parts},
        auth=auth,
        debug_api=debug_api,
        num_stacks_to_drop= debug_num_stacks_to_drop,
        session= session,
        parent_class=parent_class
    )

    

    return res

# %% ../../nbs/classes/50_DomoEnterpriseApps.ipynb 8
@gd.route_function
async def get_design_versions(
    auth: dmda.DomoAuth,
    design_id,
    debug_api: bool = False,
    debug_num_stacks_to_drop=1,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
):

    url = f"https://{auth.domo_instance}.domo.com/domoapps/designs/{design_id}/versions"

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

    if not res.is_success:
        raise App_API_Exception(res=res)

    return res

# %% ../../nbs/classes/50_DomoEnterpriseApps.ipynb 11
class Design_GET_Assets(de.DomoError):

    def __init__(self, res, design_id):

        message = f"unablto download assets for {design_id}"

        super().__init__(res=res, message=message)


@gd.route_function
async def get_design_source_code_by_version(
    auth: dmda.DomoAuth,
    design_id,
    version,
    debug_api: bool = False,
    debug_num_stacks_to_drop=1,
    parent_class: str = None,
    session: httpx.AsyncClient = None,
    download_path: str = None,  # location to download file to
    is_unpack_archive=True,
):

    url = f"http://{auth.domo_instance}.domo.com/domoapps/designs/{design_id}/versions/{version}/assets"

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

    if not res.is_success:

        raise Design_GET_Assets(res=res, design_id=design_id)

    if download_path:

        download_path = (
            dmfi.change_extension(download_path, ".zip")
            if not is_unpack_archive
            else download_path
        )

        if debug_api:
            print(f"content downloaded to - {download_path}")

        dmfi.download_zip(
            output_folder=download_path,
            zip_bytes_content=res.response,
            is_unpack_archive=is_unpack_archive,
        )

    return res

# %% ../../nbs/classes/50_DomoEnterpriseApps.ipynb 13
@gd.route_function
async def get_all_designs(
    auth: dmda.DomoAuth,
    parts: str = "owners,creator,thumbnail,versions,cards",
    debug_api: bool = False,
    debug_num_stacks_to_drop: int = 1,
    session: httpx.AsyncClient = None,
    parent_class: str = None,
):


    url = f"https://{auth.domo_instance}.domo.com/api/apps/v1/designs"


    params = {
        "checkAdminAuthority": True,
        "deleted": False,
        "direction": "desc",
        "parts": parts,
        "search": "",

        "withPermission": "ADMIN",
    }


    res = await gd.get_data(
        url=url,
        method="get",
        params=params,
        auth=auth,

        debug_api=debug_api,

        timeout=10,
        num_stacks_to_drop=debug_num_stacks_to_drop,
        session=session,
        parent_class=parent_class,
    )

    return res

# %% ../../nbs/classes/50_DomoEnterpriseApps.ipynb 15
@gd.route_function
async def get_design_permissions(
    design_id: str,
    auth: dmda.DomoAuth,
    debug_api: bool = False,
    debug_num_stacks_to_drop: int = 1,
    session: httpx.AsyncClient = None,
    parent_class: str = None,
):

    res = await get_design_by_id(
        auth=auth,
        design_id=design_id,
        parts="owners",
        debug_api=debug_api,
        debug_num_stacks_to_drop=2,
        session=session,
        parent_class=parent_class,
    )
    res.response = res.response["owners"]
    return res


def set_design_admins(
    design_id,
    auth: dmda.DomoAuth,
    user_ids: List[str],
    debug_api: bool = False,
    return_raw: bool = False,
):
    endpoint = f"/api/apps/v1/designs/{design_id}/permissions/ADMIN"

    res = dmda.domo_api_request(
        endpoint=endpoint,
        request_type="POST",
        auth=auth,
        debug_api=debug_api,
        body=user_ids,
    )
    if return_raw:
        return res

    if not res.is_success:
        raise App_API_Exception(res=res)

    res.response = f"successfully set design_id {design_id} admins to {user_ids}"

    return res


def add_design_admin(
    design_id: str, auth: dmda.DomoAuth, user_ids: List[int], debug_api: bool = False
):
    user_ids = user_ids if isinstance(user_ids, list) else [user_ids]

    res = get_design_permissions(design_id=design_id, auth=auth, debug_api=debug_api)

    user_ids = list(set([owner["id"] for owner in res.response] + user_ids))

    return set_design_admins(
        design_id=design_id, auth=auth, debug_api=debug_api, user_ids=user_ids
    )
