#
# Useful code for Part 2 of HW 11.   J. Cremer 5/6/09
# In Part 2, as part of creating the function addCity(), 
# you will need to determine distances between the new city 
# and the cities already in the graph.  The function below
# will ask Google Maps for the driving distance between two given 
# cities.
#
# You need to provide the graph as one input, since the code
# uses the lat/lng's stored with the cities for the query to 
# Google, rather than sending the given city names, city1 and city2,
# directly to Google (this second option would also work but 
# seems slightly more consistent to use the lat/lng we already 
# have as the "real" city location). 
# THUS, before calling this function you need to make sure that 
# both cities are in the graph, with at least their lats and longs
# available.  The *edges* might presumably won't all be in the graph
# (this function is helping you create them), but that's okay.
# 
# NOTE: YOU NEED TO CHANGE THE TEMP FILE NAME TO SOMETHING THAT
#       WORKS FOR YOU.
#
def getDrivingDistance(graph, city1, city2):
  tempKMLfile = '/users/cremer/Desktop/tempKMLfile.kml'

  # First construct distance query URL
  urlbase = "http://maps.google.com/maps?output=kml"
  params = []
  params.append("key=%(api_key)s" % {"api_key":api_key})  
  params.append("q=from:%(lat1)s,%(lng1)s+to:%(lat2)s,%(lng2)s" 
                % {"lat1": graph[city1][2], "lng1": -graph[city1][3],
                   "lat2": graph[city2][2], "lng2": -graph[city2][3]})
  url = "%(urlbase)s&%(params)s" % {"urlbase":urlbase,"params":"&".join(params)}
  
  # Useful for debugging if something goes wrong.
  #
  #printNow(url)

  # Use the URL - Google should return a KML file
  urllib.urlretrieve(url, tempKMLfile)

  # The KML file has lots of stuff that we don't need/want. 
  # Open it and search for the place where the distance is given. Extract it
  # and return it
  file = open(tempKMLfile, 'r')
  kmlString = (file.readlines())[0]
  distPos = kmlString.find("Distance:")
  distPos2 = kmlString.find("#", distPos)
  distString = kmlString[distPos+9:distPos2-1]
  result = int(distString.replace(",", ""))
  return(result)