import os, requests, jwt
from django.shortcuts import redirect
from django.http.request import HttpRequest
from django.http.response import HttpResponse, HttpResponseRedirect, HttpResponseForbidden
from django.urls import reverse
# from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
User = get_user_model()


def login(request):
    if request.session.get('username'):
        return HttpResponseRedirect(reverse('admin:index'))
    else:
        authorization_url = '{base_url}/authorize?response_type=code&scope=openid&client_id={client_id}&redirect_uri={redirect_uri}'.format(
            base_url=os.getenv("DJANGO_SSO_OAUTH_BASE_URL"),
            client_id=os.getenv("DJANGO_SSO_OAUTH_CLIENT_ID"),
            redirect_uri=os.getenv("DJANGO_SSO_OAUTH_REDIRECT_URL")
        )
        return redirect(authorization_url)


def http_response(content, status):
    return HttpResponse(content, status)


def oauth_redirect(request):
    auth_code = request.GET.get('code')
    if not auth_code:
        return http_response("Bad request parameters: No authorization code", 400)
    redirect_uri = os.getenv("DJANGO_SSO_OAUTH_REDIRECT_URL")
    client_id = os.getenv('DJANGO_SSO_OAUTH_CLIENT_ID')
    client_secret = os.getenv('DJANGO_SSO_OAUTH_CLIENT_SECRET')
    auth_data = {
        "client_id"    : client_id,
        "client_secret": client_secret,
        "grant_type"   : "authorization_code",
        "code"         : auth_code,
        "redirect_uri" : redirect_uri
    }
    resp = requests.request('POST', f'{os.getenv("DJANGO_SSO_OAUTH_BASE_URL")}/token', data=auth_data)
    if resp.status_code != 200:
        return http_response("Failed when request access code: {}".format(resp.text), 400)
    resp_json = resp.json()
    if not resp_json or not resp_json.get('access_token'):
        return http_response("Failed when request access code: {}".format(resp.text), 400)

    id_token = resp_json.get('access_token')
    decoded_token = jwt.decode(id_token, verify=False, algorithms=["HS256"], options={"verify_signature": False})
    # logger.info('====== Decoded token: {}'.format(decoded_token))
    if decoded_token.get('upn'):
        email = decoded_token.get('upn').lower()
    elif decoded_token.get('unique_name'):
        email = decoded_token.get('unique_name').lower()
    else:
        return http_response("User information is not found", 400)

    try:
        user = User.objects.get(username=email)
    except Exception as e:
        print(e)
        resp = HttpResponseForbidden()
        resp.content = 'You are not allowed to access this site.'
        return resp

    request.session['username'] = email
    return HttpResponseRedirect(reverse('admin:index'))
