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

ACCESS_TOKEN_URI = settings.HOST_URI + '/token'


def get_auth_header():
    # Make a header with access key for making request in google-my-business server.
    access_token = get(ACCESS_TOKEN_URI).text
    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():
    user = User.objects.filter(username='admin@ercare').first()
    uid = user.id
    user = UserModel.objects.filter(pk=uid).first()
    if user:
        refresh_token = user.refresh_token
    else:
        return None

    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