from requests import get
from .models import Location
from gauth.auth_utils import get_auth_header
from .auth_utils import get_gmb_id


def populate_locations():
    headers = get_auth_header()
    user, gmb_id = get_gmb_id()
    url = 'https://mybusiness.googleapis.com/v4/accounts/' + gmb_id + '/locations'
    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]
        loc_name = loc['address']['locality']
        loc_website = loc['websiteUrl']
        location = Location.objects.filter(location_id=loc_id).first()
        if not location:
            location = Location.objects.create(
                location_id=loc_id,
                location_name=loc_name,
                website_url=loc_website,
                owner=user
            )
        if location:
            print('A new location has been created!')