#!/usr/bin/python
""" respond to call-backs from Google generated by notifications. """

# Apache License 2.0 incorporated by reference

# Wikilocation.org
# http://wikilocation.org/documentation/#api-articles


import config
import re
import os
import sys
import json
import urllib2
import urllib
import cgi
import config

import cgitb
cgitb.enable()

# ---- write out the same thing that Google sees to security/notify.txt ----
outf = open("security/notify.txt", "w")
def output(s):
    sys.stdout.write(s)
    outf.write(s)

print "Content-Type: text/plain\n" # only needed for CGI

# ---- get our parameters ----
# Google posts to us, but we can also be called using get and a userToken

if os.environ['REQUEST_METHOD'] == 'POST':
    request = json.load(sys.stdin)
else:
    # https://.../notify.cgi?userToken=b0119336-0ae7-4f0f-9eb3-4dccac7f8b39
    request = cgi.parse_qs(os.environ['QUERY_STRING'])
    request['userToken'] = request['userToken'][0]


# ---- get our user's history ----
output('Request: %s\n' % str(request))
fn = "security/" + request['userToken']
if not os.path.exists(fn):
    output("oh dear, we don't have a record of that userToken. ")
    sys.exit()
history = json.load(open(fn))
output('History: %s\n' % str(history))
refresh_history = open(fn + ".refresh").read()
output('History: %s\n' % str(refresh_history))

# ---- get an access token using their refresh token ----
data = {}
url = "https://accounts.google.com/o/oauth2/token"
data['refresh_token'] = refresh_history
data['client_id'] = config.client_id
data['grant_type'] = 'refresh_token'

output("url: %s\n" % url)
output("data: %s\n" % data)
data['client_secret'] = config.client_secret

result = urllib2.urlopen(url, urllib.urlencode(data)).read()
results = json.loads(result)
access_token = results['access_token']

output("Results: %s\n" % str(results))

# ---- get their location ----

url = """
https://www.googleapis.com/mirror/v1/locations/latest?
access_token=%s
""".replace('\n', '') % access_token
location_results = json.load(urllib2.urlopen(url))

output("Location Results: %s\n" % str(location_results))

# ---- get the nearest Wikipedia page ----

url = """
http://api.wikilocation.org/articles?
lat=%(latitude)s&
lng=%(longitude)s&
limit=1&radius=20000m
""" .replace('\n', '') % location_results
wikilocation_results = json.load(urllib2.urlopen(url))

output("WikiLocation Results: %s\n" % str(wikilocation_results))

if not len(wikilocation_results['articles']):
    output("nothing within 20km, we're done")
    sys.exit()

wlr = wikilocation_results['articles'][0]

# ---- fetch the article content ----

url = """
http://en.wikipedia.org/w/api.php?
format=json&
action=query&
pageids=%s&
prop=extracts&
exintro=y
""" .replace('\n', '') % wlr['id']
wikipedia_results = json.load(urllib2.urlopen(url))

try:
    wpre = wikipedia_results["query"]['pages'][wlr['id']]['extract']
except:
    output("No wikipedia results:" + str(wikipedia_results))
    sys.exit()

# ---- post to their timeline ----

url = """https://www.googleapis.com/mirror/v1/timeline?
access_token=%s""".replace('\n', '') % access_token
data = {}
distance = wlr['distance']
if int(distance[:-1]) > 999:
    distance = "%.1fkm" % (float(distance[:-1]) / 1000.0)
title = wlr['title']
#data['text'] = "You are at %.3f,%.3f, %s from %s" % (float(location_results['latitude']), float(location_results['longitude']), distance, title)
data['html'] = "<article>" + wpre + "</article>"
data['canonicalUrl'] = wlr['mobileurl']
#data['speakableText'] = title
data['speakableType'] = "Description"
data['notification'] = {'level': 'DEFAULT'}
data['location'] = location_results
data['menuItems'] = [
    { 'action': 'READ_ALOUD' },
    { 'action': 'NAVIGATE' }, 
    ]

data_j = json.dumps(data)
output("Url: %s\n" % str(url))
output("Data: %s\n" % str(data))

wikiid = history.get('wikiid', None)
newid = wikilocation_results['articles'][0].get('id', None)

history['wikiid'] = wikilocation_results['articles'][0]['id']
newf = open("security/" + request['userToken'] + ".wikiid", "w")
json.dump(history, newf)
os.rename("security/" + request['userToken'] + ".wikiid", 
          "security/" + request['userToken'])

if wikilocation_results['articles'][0]['id'] != wikiid:
    req = urllib2.Request(url, data_j, {'Content-Type': 'application/json'})
    result = urllib2.urlopen(req).read()

    output("Result: %s\n" % str(request))
    output("success!")
else:
    output("same location, skipping")

