import urllib.request
import urllib.parse
import json

def getCoordinates(placeName):
    '''Takes in a string query and returns a (long, lat) tuple, both floats.
       string -> (float,float)'''

    googleGeocodeUrl ='http://maps.googleapis.com/maps/api/geocode/json?'
    query = placeName.encode('utf-8')
    params = {'address': query}

    url = googleGeocodeUrl + urllib.parse.urlencode(params)
    json_response = urllib.request.urlopen(url)
    response = json.loads(json_response.readall().decode('utf-8'))

    if response['status'] != 'OK':
      print("No response to query")
      return None, None

    print("Got response!!!")
    location = response['results'][0]['geometry']['location']
    latitude, longitude = location['lat'], location['lng']

    return latitude, longitude

def printLocation(latlonString) :
    googleGeocodeUrl ='http://maps.googleapis.com/maps/api/geocode/json?'
    query = latlonString.encode('utf-8')
    params = {'latlng': query}

    url = googleGeocodeUrl + urllib.parse.urlencode(params)
    print(url)
    json_response = urllib.request.urlopen(url)
    response = json.loads(json_response.readall().decode('utf-8'))

    if response['status'] != 'OK':
      print("No response to query")
      return None

    print("Got response!!!")
    info = response['results'][0]['address_components']

    for u in info :
        if 'country' in u['types'] :
            print(u['long_name'])

    for u in info :
        if 'administrative_area_level_1' in u['types'] :
            print(u['long_name'])

    return
