from requests import get
from .models import Location
from django.conf import settings
from .auth_utils import get_gmb_id

ACCESS_TOKEN_URI = settings.HOST_URI + '/token'


def get_all_location_ids():
    locations = Location.objects.only('location_id')
    ids = [loc.location_id for loc in locations]
    '''
    There is a location which we don't need to add into database.
    It is a Medical Billing Service, That's why it is nothing to do with review. 
    '''
    if '5397588228065547694' in ids:
        ids.remove('5397588228065547694')
    return ids


def populate_locations():
    access_token = get(ACCESS_TOKEN_URI).text
    user, gmb_id = get_gmb_id()
    url = 'https://mybusiness.googleapis.com/v4/accounts/' + gmb_id + '/locations'
    headers = {
        'authorization': 'Bearer ' + access_token,
        'content-type': 'application/json'
    }
    res = get(url, headers=headers).json()
    locations = res['locations']
    for loc in locations:
        # loc['name'] = 'accounts/103266181421855655295/locations/8916258876770296726'
        loc_id = loc['name'].split('/')[-1]
        location_ids = get_all_location_ids()
        location_ids.append('5397588228065547694')
        if loc_id in location_ids:
            continue
        loc_name = loc['address']['locality']
        loc_website = loc['websiteUrl']
        loc_display = loc['primaryCategory']['displayName']
        location = Location.objects.create(location_id=loc_id, location_name=loc_name, website_url=loc_website, display_name=loc_display, owner=user)
        location.save()