import os
from django.http import HttpResponse
from django.shortcuts import redirect
import google_auth_oauthlib.flow
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.conf import settings
from .auth_utils import get_access_token, get_google_account_id

from .models import UserModel

base_dir = settings.BASE_DIR

CLIENT_SECRETS_FILE = os.path.join(base_dir, "client_secrets.json")
SCOPES = ['https://www.googleapis.com/auth/business.manage']
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE,
        scopes=SCOPES,
        redirect_uri="http://127.0.0.1:8000/oauth2callback")


def get_token(request):
    get_access_token(request)
    cred = request.session['credentials']
    return HttpResponse(cred.get('access_token'))


@login_required
def google_auth(request):
    user = User.objects.filter(username='admin@ercare').first()
    if not user:
        return HttpResponse('<h1>You have to have a user account with username "admin@ercare".'
                            ' Please create a superuser using manage.py createsuperuser</h2>')
    return redirect('authorize')


def authorize(request):
    authorization_url, state = flow.authorization_url(access_type='offline', include_granted_scopes='true')

    # Store the state so the callback can verify the auth server response.
    request.session['state'] = state

    return redirect(authorization_url)


def oauth2callback(request):
    state = request.session['state']

    flow.state = state
    code = request.GET.get('code', False)
    flow.fetch_token(code=code)
    credentials = flow.credentials
    account_id = get_google_account_id(credentials.token)
    user = User.objects.filter(username='admin@ercare').first()
    user_model, created = UserModel.objects.get_or_create(user=user)
    user_model.refresh_token = credentials.refresh_token
    user_model.gmb_account_id = account_id
    user_model.save()
    request.session['credentials'] = credentials_to_dict(credentials)
    return redirect('token')


def credentials_to_dict(credentials):
    expiry = str(credentials.expiry.utcnow())
    return {
        'access_token': credentials.token,
        'expiry': expiry
    }
