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

# %% auto 0
__all__ = ['generate_config_auth', 'Config_GenerateConfigAuth', 'get_domoaccount', 'Config_DomoJupyterToDomoAccount',
           'upsert_domoaccount', 'Config_UpsertDomoAccount']

# %% ../nbs/00_FactoryAuth.ipynb 1
from domolibrary_extensions.utils.factory import (
    factory_function,
    FactoryLogs, 
    FactoryResponse, FactoryConfig, FactoryMessage)

from domolibrary.client.DomoAuth import DomoAuth


# %% ../nbs/00_FactoryAuth.ipynb 2
import httpx
from dataclasses import dataclass, field
from typing import List, Callable

import domolibrary.classes.DomoAccount as dmac

# %% ../nbs/00_FactoryAuth.ipynb 4
@factory_function(config_id_col = "domo_instance")
async def generate_config_auth(config, 
                               res : FactoryResponse,
                               logs : FactoryLogs,
                               session : httpx.AsyncClient = None,  
                               debug_api : bool = False):
    
    config_auth_standard = config.config_auth_standard
    config_auth_exception = config.config_auth_exception
    
    domo_instance = config.domo_instance
    
    res.location = domo_instance    
    step = FactoryMessage(stage = 'generate_config_auth', message = 'using standard auth')
    res.add_message(step)
    auth = config_auth_standard
    step.is_success = True
    
    if config.target_instance_use_exception_pw == 1:
        auth = config_auth_exception
        step.message = "using exception auth"
        step.is_success = True
        
    auth.domo_instance = domo_instance

    step = FactoryMessage(stage = 'test is valid auth')
    res.add_message(step)
        
    try:
        await auth.print_is_token()
        step.is_success = True
        step.message = 'valid auth'
         
    except Exception as e:
        step.message = e
        step.is_success = False
        
    config.auth = auth
    res.response = auth
    return res

# %% ../nbs/00_FactoryAuth.ipynb 5
@dataclass
class Config_GenerateConfigAuth(FactoryConfig):
    config_auth_exception : DomoAuth = None
    config_auth_standard : DomoAuth = None
    domo_instance : str = None
    target_instance_use_exception_pw : int = None
    factory_fn_ls : List[Callable] = field(default_factory =  lambda : [generate_config_auth])

# %% ../nbs/00_FactoryAuth.ipynb 6
@factory_function(config_id_col = "account_name")
async def get_domoaccount(
    config,
    res : FactoryResponse,
    logs : FactoryLogs,
    session : httpx.AsyncClient = None,  
    debug_api : bool = False
    ) -> FactoryResponse:
    
    account_name = config.account_name
    domojupyter_fn = config.domojupyter_fn
    is_abstract = config.account_is_abstract
    
    
    
    
    if not account_name or not domojupyter_fn or is_abstract is None:
        raise Exception("must pass account_name, dj_fn, and config_is_abstract")
    
    step = FactoryMessage(stage = 'get domojupyter creds')
    res.add_message(step)
    
    creds = None
    try:    
        creds = dxut.read_domo_jupyter_account(account_name = account_name, 
                                               domojupyter_fn = domojupyter_fn, 
                                               is_abstract = is_abstract)
        step.is_success = True
        step.message = creds
    
    except Exception as e:
        step.is_success = False
        step.message = e
    
    if not creds:
        res.response = 'no creds'
        return res
    
    step = FactoryMessage(stage = 'get config for account')
    res.add_message(step)

    config = None
    if not is_abstract:
        config = dmac.AccountConfig.domo_access_token.value
        config = config(username = creds['username'],
               password = creds['password'],
               domo_access_token = creds['domoAccessToken'])
    

        
    creds = {"access_token" : access_token,
             "password" : creds['DOMO_PASSWORD'] if is_abstract else creds['password'],
             "username" :creds['DOMO_USERNAME'] if is_abstract else creds['username'],
             "account_name" : account_name 
            }
    
    step.message = "reformated creds output"
    return creds

@dataclass
class Config_DomoJupyterToDomoAccount(FactoryConfig):
    account_name : str = None, 
    domojupyter_fn : Callable = None,
    account_is_abstract : bool = None, 
    # domo_instance : str = None
    factory_fn_ls : List[Callable] = field(default_factory =  lambda : [domojupyter_account_to_domoaccount])

# %% ../nbs/00_FactoryAuth.ipynb 7
@factory_function(config_id_col = "account_name")
async def upsert_domoaccount(
    config,
    res : FactoryResponse,
    logs : FactoryLogs,
    session : httpx.AsyncClient = None,
    debug_api: bool = False
):
    access_token = config.access_token or ""
    username = config.email or ""
    password = config.password or ""
    account_name = config.account_name
    auth = config.auth
    config_auth = config.config_auth
    
    res.location = auth.domo_instance

    step = FactoryMessage( stage="upsert domo account", is_success=False)
    res.add_message( step )
    
    account_config = dmac.AccountConfig['domo_access_token'].value(
        domo_access_token = access_token,
        username = username,
        password = password
    )
    
    domo_account = None
    try:
        domo_account = await dmac.DomoAccounts.upsert_account(
            auth = auth,
            account_config = account_config,
            account_name = account_name,
            session = session,
            debug_api = debug_api
        )
        step.is_success = True
        step.message = 'account upserted'
        
    except Exception as e:
        step.message = e
        step.is_success = False
        
    if config_auth:
        step = FactoryMessage( stage="upsert config instance", is_success=False)
        res.add_message( step )
    
        try:
            domo_account = await dmac.DomoAccounts.upsert_account(
                auth = config_auth,
                account_config = account_config,
                account_name = account_name,
                session = session,
                debug_api = False
            )
            step.is_success = True
            step.message = 'account upserted'
        
        except Exception as e:
            step.message = e
            step.is_success = False
           
    config.domo_account = domo_account
    res.response = domo_account or 'no account'
        
    return res

@dataclass
class Config_UpsertDomoAccount(FactoryConfig):
    account_name : str = None 
    access_token : str = ""
    username : str = ""
    password : str = ""
    
    factory_fn_ls : List[Callable] = field(default_factory =  lambda : [upsert_domoaccount])
