"""Fill in a module description here"""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/utils/domojupyter.ipynb.

# %% auto 0
__all__ = ['which_environment', 'DJ_Workspace_NoAuth', 'read_domo_jupyter_account', 'get_creds_from_domojupyter_account',
           'DJ_Workspace_InvalidCreds', 'generate_token_auth', 'generate_full_auth', 'generate_domo_auth']

# %% ../../nbs/utils/domojupyter.ipynb 2
from typing import Callable

import os
import json

from operator import itemgetter
import urllib.parse as urllib_parse

import domolibrary_execution.client.ExecutionError as dxde

import domolibrary.client.DomoError as dmde
import domolibrary.client.DomoAuth as dmda
import domolibrary.classes.DomoAccount as dmacc
import domolibrary.classes.DomoInstanceConfig as dmic
import domolibrary.classes.DomoUser as dmdu
import domolibrary.classes.DomoRole as dmdr

import domolibrary.utils.chunk_execution as dmce
import domolibrary_extensions.utils.execution as dtex


from nbdev.showdoc import patch_to

# %% ../../nbs/utils/domojupyter.ipynb 4
def which_environment():
    return urllib_parse.urlparse(os.environ.get("DOMO_HOSTNAME")).netloc.replace(
        ".domo.com", ""
    )

# %% ../../nbs/utils/domojupyter.ipynb 5
class DJ_Workspace_NoAuth(dxde.ExecutionError):
    def __init__(self, account_name, message):
        super().__init__(f"{account_name} - {message}")


@dtex.auto_retry_sync()
def read_domo_jupyter_account(
    account_name,
    domojupyter_fn: Callable,
    is_abstract: bool = False,
    is_dict: bool = True,
):
    creds = None
    try:
        account_properties = domojupyter_fn.get_account_property_keys(account_name)

        creds = {
            prop: domojupyter_fn.get_account_property_value(account_name, prop)
            for prop in account_properties
        }
    except Exception as e:
        raise DJ_Workspace_NoAuth(
            account_name=account_name,
            message= f"🤯🤯 unable to retrieve {account_name} - {e}",
        ) from e

    if not is_abstract:
        return creds

    creds = creds["credentials"]

    if not is_dict:
        return creds.strip()

    return json.loads(creds)

# %% ../../nbs/utils/domojupyter.ipynb 6
def remove_asterix(text):
    if text == "" or text == "********":
        return None
    return text

# %% ../../nbs/utils/domojupyter.ipynb 7
def get_creds_from_domojupyter_account(
    account_name: str,
    domojupyter_fn: Callable,
    is_abstract: bool,
) -> dict:

    creds = read_domo_jupyter_account(
        account_name, domojupyter_fn, is_abstract=is_abstract
    )

    creds = {
        "access_token": (
            creds.get("DOMO_ACCESS_TOKEN")
            if is_abstract
            else creds.get("domoAccessToken")
        ),
        "password": (
            creds.get("DOMO_PASSWORD") if is_abstract else creds.get("password")
        ),
        "username": (
            creds.get("DOMO_USERNAME") if is_abstract else creds.get("username")
        ),
    }

    creds = {key: remove_asterix(value) for key, value in creds.items()}

    return creds

# %% ../../nbs/utils/domojupyter.ipynb 8
class DJ_Workspace_InvalidCreds(dxde.ExecutionError):
    def __init__(self, account_name, message):
        super().__init__(f"{account_name} - {message}")


async def generate_token_auth(
    domo_instance: str,
    domojupyter_fn: Callable,
    account_name: str = None,
    is_include_domo_account: bool = False,
    is_abstract: bool = False,
):

    account_name = account_name or f"sdk_{domo_instance}"

    creds = get_creds_from_domojupyter_account(
        account_name=account_name,
        domojupyter_fn=domojupyter_fn,
        is_abstract=is_abstract,
    )

    domo_access_token = creds.get("access_token")

    if not domo_access_token:
        raise DJ_Workspace_InvalidCreds(
            account_name=account_name, message="no access token stored in account"
        )

    auth = dmda.DomoTokenAuth(
        domo_instance=domo_instance, domo_access_token=domo_access_token
    )

    await auth.print_is_token()

    if is_include_domo_account:
        domo_accounts = await dmacc.DomoAccounts.get_accounts(auth=auth)
        domo_account = next((acc for acc in domo_accounts if acc.name == account_name))
        return auth, domo_account

    return auth

# %% ../../nbs/utils/domojupyter.ipynb 9
async def generate_full_auth(
    domo_instance: str,
    domojupyter_fn: Callable,
    account_name : str = None, #defauls to sdk_domo_instance
    is_include_domo_account: bool = False,
    is_abstract: bool = False,
):

    account_name = account_name or f"sdk_{domo_instance}"

    creds = get_creds_from_domojupyter_account(
        account_name=account_name,
        domojupyter_fn=domojupyter_fn,
        is_abstract=is_abstract,
    )

    domo_username = creds.get("username")
    if not domo_username:
        raise DJ_Workspace_InvalidCreds(
            account_name=account_name, message="no username stored in account"
        )

    domo_password = creds.get("password")
    if not domo_password:
        raise DJ_Workspace_InvalidCreds(
            account_name=account_name, message="no password stored in account"
        )

    auth = dmda.DomoFullAuth(
        domo_instance=domo_instance,
        domo_username=domo_username,
        domo_password=domo_password,
    )

    await auth.print_is_token()

    if is_include_domo_account:
        domo_accounts = await dmacc.DomoAccounts.get_accounts(auth=auth)
        domo_account = next((acc for acc in domo_accounts if acc.name == account_name))
        return auth, domo_account

    return auth

# %% ../../nbs/utils/domojupyter.ipynb 10
async def generate_domo_auth(
    domo_instance: str,
    domojupyter_fn: Callable,
    account_name : str = None,
    is_include_domo_account: bool = False,
    is_abstract: bool = False,
    backup_auth: dmda.DomoAuth = None
):
    account_name = account_name or f"sdk_{domo_instance}"

    try:
        return await generate_full_auth(
            account_name= account_name,
            domo_instance=domo_instance,
            domojupyter_fn=domojupyter_fn,
            is_include_domo_account=is_include_domo_account,
            is_abstract=is_abstract,
        )
    except (dmde.DomoError, dxde.ExecutionError) as e:
        print(e)
        pass

    try:        
        return await generate_token_auth(
            account_name= account_name,
            domo_instance=domo_instance,
            domojupyter_fn=domojupyter_fn,
            is_include_domo_account=is_include_domo_account,
            is_abstract=is_abstract,
        )
    except (dmde.DomoError, dxde.ExecutionError) as e:
        print(e)
        pass

    if not backup_auth:
        raise DJ_Workspace_NoAuth(account_name = account_name, message = f"no valid creds in {account_name}.  Pass backup account or update creds")

    if not backup_auth.is_valid_token:
        await backup_auth.print_is_token()

    return backup_auth




    
