from uncloud.common.shared import shared
from pyotp import TOTP


def get_token(seed):
    if seed is not None:
        try:
            token = TOTP(seed).now()
        except Exception:
            raise Exception('Invalid seed')
        else:
            return token


def resolve_otp_credentials(kwargs):
    d = {
        'name': shared.settings['client']['name'],
        'realm': shared.settings['client']['realm'],
        'token': get_token(shared.settings['client']['seed'])
    }

    for k, v in d.items():
        if k in kwargs and kwargs[k] is None:
            kwargs.update({k: v})

    return d
