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

# %% auto 0
__all__ = ['BeastModes_API_Error', 'Search_BeastModeLink', 'generate_beastmode_body', 'search_beastmodes', 'lock_beastmode',
           'get_beastmode_by_id', 'get_card_beastmodes']

# %% ../../nbs/routes/beastmode.ipynb 3
from typing import List
import httpx
from enum import Enum

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

# %% ../../nbs/routes/beastmode.ipynb 5
class BeastModes_API_Error(de.DomoError):
    def __init__(self, status, domo_instance, function_name, message, parent_class = None):
        super().__init__(status = status, domo_instance = domo_instance, parent_class = parent_class, function_name = function_name)

try:
    raise BeastModes_API_Error(400, 'test_instance', 'hello-world', 'this  is great')
except BeastModes_API_Error as e:
    print(e)

# %% ../../nbs/routes/beastmode.ipynb 6
class Search_BeastModeLink(Enum):
    CARD = 'CARD'
    DATASOURCE = 'DATA_SOURCE'

def generate_beastmode_body(name: str = None, 
                            filters : List[dict] = None, 
                            is_unlocked: bool = None,
                            is_not_variable : bool = None,
                            link : Search_BeastModeLink = None
                             ):
    filters = filters or []
    
    body = {}
    if name: body.update({'name' : name})

    return {"name":"","filters":[{"field":"notvariable"}, *filters],"sort":{"field":"name","ascending":True}}

@gd.route_function
async def search_beastmodes(auth :dmda.DomoFullAuth, filters : List[dict] = None, 
                            session :httpx.AsyncClient = None, debug_api:bool = False, debug_num_stacks_to_drop = 1, debug_loop : bool = False, 
                            parent_class = None,
                            return_raw: bool = False):

    offset_params = {
        "offset": "offset",
        "limit": "limit",
    }
    url = f"https://{auth.domo_instance}.domo.com/api/query/v1/functions/search"

    body = generate_beastmode_body(filters)


    def arr_fn(res) -> list[dict]:
        return res.response['results']

    res = await gd.looper(
        auth=auth,
        method="POST",
        url=url,
        arr_fn=arr_fn,
        body=body,
        offset_params_in_body=True,
        offset_params=offset_params,
        loop_until_end=True,
        session=session,
        debug_loop=debug_loop,
        debug_api=debug_api,
        return_raw = return_raw,
        debug_num_stacks_to_drop=debug_num_stacks_to_drop,
        parent_class=parent_class,
    )

    if not res.is_success:
        raise BeastModes_API_Error(status = res.status, 
            domo_instance = auth.domo_instance, 
            message = res.response, 
            function_name = res.traceback_details.function_name, 
            parent_class = parent_class)

    return res




# %% ../../nbs/routes/beastmode.ipynb 8
@gd.route_function
async def lock_beastmode(beastmode_id, 
    is_locked: bool,
    auth : dmda.DomoFullAuth,
    session: httpx.AsyncClient = None,
    debug_api : bool = False,
    debug_num_stacks_to_drop=1,
    parent_class : str = None ):

    url = f'https://{auth.domo_instance}.domo.com/api/query/v1/functions/template/{beastmode_id}'

    body = {"locked":is_locked}

    res = await gd.get_data(
        auth=auth,
        method="PUT",
        url=url,
        body=body,
        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 BeastModes_API_Error(status = res.status, 
            domo_instance = auth.domo_instance, 
            message = res.response, 
            function_name = res.traceback_details.function_name, 
            parent_class = parent_class)
    
    return res


# %% ../../nbs/routes/beastmode.ipynb 10
@gd.route_function
async def get_beastmode_by_id(beastmode_id, 
    auth : dmda.DomoFullAuth,
    session: httpx.AsyncClient = None,
    debug_api : bool = False,
    debug_num_stacks_to_drop=1,
    parent_class : str = None ):

    url = f'https://{auth.domo_instance}.domo.com/api/query/v1/functions/template/{beastmode_id}'


    res = await gd.get_data(
        auth=auth,
        method="GET",
        url=url,
        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 BeastModes_API_Error(status = res.status, 
            domo_instance = auth.domo_instance, 
            message = res.response, 
            function_name = res.traceback_details.function_name, 
            parent_class = parent_class)
    
    return res


# %% ../../nbs/routes/beastmode.ipynb 12
async def get_card_beastmodes(
    card_id,
    auth: dmda.DomoAuth,
    debug_api: bool = False,
    session: httpx.AsyncClient = None,
    debug_num_stacks_to_drop=2,
    return_raw: bool = False,
):


    all_bms = (
        await search_beastmodes(
            auth=auth,
            debug_api=debug_api,
            session=session,
            debug_num_stacks_to_drop=debug_num_stacks_to_drop,
        )
    ).response


    filter_bms = [
        bm
        for bm in all_bms
        if any([True for link in bm["links"] if link["resource"]["type"] == "CARD" and link["resource"]["id"] == card_id])
    ]


    if return_raw:
        return filter_bms

    return [
        {
            "id": bm["id"],
            "name": bm["name"],
            "locked": bm["locked"],
            "legacyId": bm["legacyId"],
            "status": bm["status"],
            "links": bm["links"],
        }
        for bm in filter_bms
    ]
