# AUTOGENERATED! DO NOT EDIT! File to edit: ../../nbs/00_utils.ipynb.

# %% auto 0
__all__ = ['which_environment', 'read_domo_jupyter_account', 'domojupyter_to_domoauth']

# %% ../../nbs/00_utils.ipynb 2
import os 
import urllib.parse as urllib_parse
import json


from operator import itemgetter

import json
from typing import Callable

import domolibrary.client.DomoAuth as dmda

# %% ../../nbs/00_utils.ipynb 3
def which_environment():
    return urllib_parse.urlparse(os.environ.get('DOMO_HOSTNAME')).netloc.replace('.domo.com', '')
    

# %% ../../nbs/00_utils.ipynb 4
def read_domo_jupyter_account(account_name,
                              domojupyter_fn : Callable,
                              is_abstract: bool = False,
                              is_dict : bool = True
                            
                             ):

    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
    }

    if not is_abstract:
        return creds

    creds = creds['credentials']
    
    if not is_dict:
        return creds.strip()
    
    return json.loads(
        creds
    )

# %% ../../nbs/00_utils.ipynb 5
def remove_asterix(text):
    if text == '' or text == '********':
        return None
    return text

# %% ../../nbs/00_utils.ipynb 6
async def domojupyter_to_domoauth(
    account_name,
    instance,
    domojupyter_fn: Callable,
    is_abstract: bool,
    is_test: bool = True
) -> dict:

    creds = None
      
    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()}
    
    access_token, password, username = itemgetter('access_token', 'password', 'username')(creds)
    
    
    auth = None
    if not auth and access_token:
        auth = dmda.DomoTokenAuth(
            domo_instance = instance,
            domo_access_token = access_token
        )
        
        if is_test and not ( await auth.print_is_token()):
            auth = None
    
    if not auth and username and password:
        auth = dmda.DomoFullAuth(
            domo_instance = instance,
            domo_username = username,
            domo_password = password
        )
        
    if is_test and not ( await auth.print_is_token()):
        auth = None
    
    if not auth:
        raise Exception(f"unable to export auth from {account_name}")

                        
    return auth

