from . import access
import agilicus
import jwt

CONTEXT = None
API_DEFAULT = "https://api.agilicus.com"
CACERT_DEFAULT = True
CLIENT_ID_DEFAULT = "admin-portal"
ISSUER_DEFAULT = "https://auth.cloud.agilicus.dev"
HEADER_DEFAULT = True
ORG_ID_DEFAULT = ""


class ApiHelper:
    def __init__(self, ctx, token):
        self.configuration = agilicus.Configuration()
        self.configuration.host = get_value(ctx, "API")
        cacert = get_value(ctx, "CACERT")
        if cacert is not True:
            self.configuration.ssl_ca_cert = cacert
        if token:
            self.configuration.access_token = token
        else:
            self.configuration.access_token = get_token(ctx)
        self.org_api = agilicus.OrganisationsApi(agilicus.ApiClient(self.configuration))
        self.application_api = agilicus.ApplicationsApi(
            agilicus.ApiClient(self.configuration)
        )
        self.app_services_api = agilicus.ApplicationServicesApi(
            agilicus.ApiClient(self.configuration)
        )
        self.user_api = agilicus.UsersApi(agilicus.ApiClient(self.configuration))
        self.logs_api = agilicus.DiagnosticsApi(agilicus.ApiClient(self.configuration))
        self.metrics_api = agilicus.MetricsApi(agilicus.ApiClient(self.configuration))
        self.issuers_api = agilicus.IssuersApi(agilicus.ApiClient(self.configuration))
        self.tokens_api = agilicus.TokensApi(agilicus.ApiClient(self.configuration))
        self.audits_api = agilicus.AuditsApi(agilicus.ApiClient(self.configuration))
        self.catalogues_api = agilicus.CataloguesApi(
            agilicus.ApiClient(self.configuration)
        )
        self.permissions_api = agilicus.PermissionsApi(
            agilicus.ApiClient(self.configuration)
        )
        self.challenges_api = agilicus.ChallengesApi(
            agilicus.ApiClient(self.configuration)
        )


def setup(ctx):
    ctx.ensure_object(dict)
    ctx.obj.setdefault("API", API_DEFAULT)
    ctx.obj.setdefault("CACERT", CACERT_DEFAULT)
    ctx.obj.setdefault("CLIENT_ID", CLIENT_ID_DEFAULT)
    ctx.obj.setdefault("ISSUER", ISSUER_DEFAULT)
    ctx.obj.setdefault("ISSUER", ISSUER_DEFAULT)
    ctx.obj.setdefault("ORG_ID", ORG_ID_DEFAULT)
    ctx.obj.setdefault("HEADER", HEADER_DEFAULT)
    save(ctx)


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, refresh=None):
    token = get_value(ctx, "TOKEN")
    if not token:
        access_token = access.get_access_token(ctx, refresh=refresh)
        token = access_token.get()
    return token


def get_apiclient_from_ctx(ctx, refresh=None):
    return get_apiclient(ctx, get_token(ctx, refresh))


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


def save(ctx):
    global CONTEXT
    CONTEXT = ctx


def get_apiclient(ctx, user_token=None):
    api = ApiHelper(ctx, user_token)
    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_scopes(ctx):
    return get_value(ctx, "SCOPES")


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"]
