import agilicus
import jwt

CONTEXT = None


class ApiHelper:
    def __init__(self):
        pass


def get_value(ctx, value):
    if value in ctx.obj:
        return ctx.obj[value]
    if value in CONTEXT.obj:
        return CONTEXT.obj[value]


def get_token(ctx):
    return get_value(ctx, "TOKEN")


def header(ctx):
    return get_value(ctx, "HEADER")


def save(ctx):
    global CONTEXT
    CONTEXT = ctx


def get_apiclient(ctx, user_token=None):
    api = ApiHelper
    api.configuration = agilicus.Configuration()
    api.configuration.host = get_value(ctx, "API")
    cacert = get_value(ctx, "CACERT")
    if cacert is not True:
        api.configuration.ssl_ca_cert = cacert
    if user_token:
        api.configuration.access_token = user_token
    else:
        api.configuration.access_token = get_value(ctx, "TOKEN")
    api.org_api = agilicus.OrganisationsApi(agilicus.ApiClient(api.configuration))
    api.application_api = agilicus.ApplicationsApi(agilicus.ApiClient(api.configuration))
    api.app_services_api = agilicus.ApplicationServicesApi(
        agilicus.ApiClient(api.configuration)
    )
    api.user_api = agilicus.UsersApi(agilicus.ApiClient(api.configuration))
    api.metrics_api = agilicus.MetricsApi(agilicus.ApiClient(api.configuration))
    api.issuers_api = agilicus.IssuersApi(agilicus.ApiClient(api.configuration))
    return api


def get_api(ctx):
    return get_value(ctx, "API")


def get_cacert(ctx):
    return get_value(ctx, "CACERT")


def get_client_id(ctx):
    return get_value(ctx, "CLIENT_ID")


def get_auth_local_webserver(ctx):
    return get_value(ctx, "AUTH_LOCAL_WEBSERVER")


def get_client_secret(ctx):
    return get_value(ctx, "CLIENT_SECRET")


def get_issuer(ctx):
    return get_value(ctx, "ISSUER")


def get_org(ctx):
    return get_value(ctx, "ORGANISATION")


def get_org_id(ctx, user_token=None):
    # first check to see if an org is chosen
    # via context/env
    if get_value(ctx, "ORG_ID") and get_value(ctx, "ORG_ID"):
        return get_value(ctx, "ORG_ID")

    # Next check to see if a token was passed in via
    # context/env
    if get_value(ctx, "TOKEN"):
        token = jwt.decode(get_value(ctx, "TOKEN"), verify=False)
        if "org_id" in token:
            return token["org_id"]

    # finally check to see if the users token
    # has an org
    if user_token:
        token = jwt.decode(user_token, verify=False)
        if "org" in token:
            return token["org"]
