from authlib.integrations.django_client import OAuth
from django.conf import settings

from oauth.models import OAuth2Token


# https://docs.authlib.org/en/latest/client/frameworks.html#frameworks-clients
def fetch_token(name, request):
    try:
        token = OAuth2Token.objects.get(
            user=request.user
        )
        return token.to_token()
    except (OAuth2Token.DoesNotExist, TypeError):
        return None


oauth = OAuth(fetch_token=fetch_token)
oauth.register(
    name='hep',
    client_id=settings.AUTHLIB_OAUTH_CLIENTS['hep']['client_id'],
    client_secret=settings.AUTHLIB_OAUTH_CLIENTS['hep']['client_secret'],
    request_token_url=settings.AUTHLIB_OAUTH_CLIENTS['hep']['request_token_url'],
    request_token_params=None,
    access_token_url=settings.AUTHLIB_OAUTH_CLIENTS['hep']['access_token_url'],
    access_token_params=None,
    authorize_url=settings.AUTHLIB_OAUTH_CLIENTS['hep']['authorize_url'],
    authorize_params=None,
    api_base_url=settings.AUTHLIB_OAUTH_CLIENTS['hep']['api_base_url'],
    client_kwargs=settings.AUTHLIB_OAUTH_CLIENTS['hep']['client_kwargs'],
)

