import os
import traceback

from django.conf import settings
from django.http import HttpResponse, JsonResponse
from google.oauth2 import id_token
from google.auth.transport import requests

from server.configs import AppConfigs

TINYCLOUD_AUTH_COOKIE_NAME = 'TINYCLOUD_AUTH_TOKEN'


def _GetAdminEmail():
  return AppConfigs.get("admin_email")


def GetGapiClientId():
  return AppConfigs.get("gapi_client_id")


def GetAuthToken(request):
  return request.COOKIES.get(TINYCLOUD_AUTH_COOKIE_NAME, '')


def SetAuthToken(response, token):
  max_age = 20 * 60 * 60  # 20 hrs
  response.set_cookie(TINYCLOUD_AUTH_COOKIE_NAME, token, max_age=max_age)


def DeleteAuthToken(response):
  response.delete_cookie(TINYCLOUD_AUTH_COOKIE_NAME)


def GetAuthEnvironment(token):
  if settings.TMC_DISABLE_AUTH:
    return {
      'email': 'test@gmail.com',
      'name': 'Test User',
      'image_url': '',
      'is_logged_in': True, 
      'is_admin': True,
    }

  try:
    idinfo = id_token.verify_oauth2_token(
        token, requests.Request(), GetGapiClientId())
    email = idinfo.get('email', '')
    return {
      'email': email,
      'name': idinfo.get('name', ''),
      'image_url': idinfo.get('picture', ''),
      'is_admin': (email == _GetAdminEmail()),
      'is_logged_in': True,
    }
  except Exception as e:
    return {'is_logged_in': False, 'reason': str(e)}


def RequireAuth(func):
  """Function wrapper to authenticate the requesting user or return 401."""
  def func_wrapper(request, *args, **kwargs):
    auth_token = GetAuthToken(request)
    auth_env = GetAuthEnvironment(auth_token)
    if not auth_env.get('is_admin', False):
      return HttpResponse('Unauthorized', status=401)
    request.auth_env = auth_env
    return func(request, *args, **kwargs)
  return func_wrapper
