from django.contrib.auth.models import User
from django.utils import timezone
from requests import post
from django.conf import settings
from .models import UserModel
from requests import get


def get_access_token(user_model):
    if user_model.expiry > timezone.now():
        return user_model.access_token
    else:
        access_token, expires_in = refresh_access_token(user_model.refresh_token)
        user_model.access_token = access_token
        user_model.expiry = timezone.now() + timezone.timedelta(seconds=expires_in)
        user_model.save()
        return access_token


def get_auth_header():
    user = User.objects.get(username='admin@ercare')
    user_model = UserModel.objects.get(user=user)
    access_token = get_access_token(user_model)
    headers = {
        'authorization': 'Bearer ' + access_token,
        'content-type': 'application/json'
    }
    return headers


# def has_expired(credentials):
#     expiry_time = credentials['expiry']
#     now = str(timezone.datetime.now())
#     return now > expiry_time


# def get_access_token(request):
#     if 'credentials' in request.session and not has_expired(request.session['credentials']):
#         cred = request.session['credentials']
#         return cred['access_token']
#     access_token, expires_in = refresh_access_token()
#     expired_at = timezone.datetime.now() + timezone.timedelta(seconds=expires_in)
#     expiry = str(expired_at)
#     credentials = {
#         'access_token': access_token,
#         'expiry': expiry
#     }
#     request.session['credentials'] = credentials
#     return credentials['access_token']


def refresh_access_token(refresh_token):
    client_id = settings.CLIENT_ID
    client_secret = settings.CLIENT_SECRET
    token_uri = settings.TOKEN_URI
    params = {
        "grant_type": "refresh_token",
        "client_id": client_id,
        "client_secret": client_secret,
        "refresh_token": refresh_token
    }

    response = post(token_uri, data=params).json()
    access_token = response.get('access_token')
    expires_in = response.get('expires_in')
    return access_token, expires_in


def get_google_account_id(access_token):
    uri = 'https://mybusiness.googleapis.com/v4/accounts'
    headers = {
        'authorization': 'Bearer '+access_token,
        'content-type': 'application/json'
    }
    res = get(uri, headers=headers).json()
    accounts_name = res['accounts'][0]['name']
    id = accounts_name.split('/')[-1]
    return id


def get_gmb_id():
    user = User.objects.get(username='admin@ercare')
    gmb_id = UserModel.objects.get(user=user).gmb_account_id
    return user, gmb_id