#!/usr/bin/env python
#

"""
gweather: Display weather using Google Weather API
"""

import json
import os
import random
import sys
import xml.dom.minidom
from optparse import OptionParser

try:
    from urllib.request import urlopen
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlopen, urlencode

Lterm_cookie = os.getenv("GRAPHTERM_COOKIE", "")
Html_escapes = ["\x1b[?1155;%sh" % Lterm_cookie,
                "\x1b[?1155l"]

def wrap(html):
    return Html_escapes[0] + html + Html_escapes[1]

Google_weather_url = "http://www.google.com/ig/api?"
Google_img_url = "http://www.google.com/ig/images/weather"

title_template = """
<b>Current weather in %(city)s</b><br>
"""
cur_template = """
<div>
<img src="http://www.google.com%(icon)s" alt="%(condition)s"> <span class="weather-item">%(temp_f)s &deg;F,</span> <span class="weather-item">%(condition)s</span><p>
<b>Forecast</b>
</div>
"""

fcst_template = """
<div>
<img src="http://www.google.com%(icon)s" alt="%(condition)s"> <span class="weather-item">%(day_of_week)s:</span> <span class="weather-item">%(condition)s,</span> <span class="weather-item">Low %(low)s &deg;F,</span> <span class="weather-item">High %(high)s &deg;F</span>
</div>
"""

form_template =  """<div class="gterm-form">Please specify location for weather info:
    <input id="gweather-input%s" name="arg1" type="text" autocomplete="off" autofocus="autofocus"></input><p>
<input id="gterm-form-command-%s" class="gterm-form-button gterm-form-command" type="submit" data-gtermformnames="arg1"></input>
<input class="gterm-form-button gterm-form-cancel" type="button" value="Cancel"></input>
</div>"""

usage = "usage: %prog [-f] <location>"
parser = OptionParser(usage=usage)
parser.add_option("-f", "--fullpage",
                  action="store_true", dest="fullpage", default=False,
                  help="Fullpage display")
parser.add_option("-t", "--text",
                  action="store_true", dest="text", default=False,
                  help="Plain text display")

(options, args) = parser.parse_args()
location = " ".join(args)

if not sys.stdout.isatty():
    options.text = True

params = {"scroll": "top", "current_directory": os.getcwd()}
params["display"] = "fullpage" if options.fullpage else "block"

headers = {"content_type": "text/html"}
headers["x_gterm_response"] = "pagelet"
headers["x_gterm_parameters"] = params

if not location:
    if not Lterm_cookie or options.text:
        print >> sys.stderr, "Please specify location"
        sys.exit(1)
    random_id = "1%09d" % random.randrange(0, 10**9)
    form_html = form_template % (random_id, random_id)
    params["display"] = "fullpage"
    params["form_input"] = True
    params["form_command"] = "gweather -f"
    print wrap(json.dumps(headers)+"\n\n"+form_html)
    sys.exit(1)
    
def xml2dict(root_elem, schema):
    retval = {}
    for key, value in schema.iteritems():
        lst = []
        retval[key] = lst
        for elem in dom.documentElement.getElementsByTagName(key):
            if isinstance(value, dict):
                vals = xml2dict(elem, value)
            else:
                vals = {}
                for key2 in value:
                    vals[key2] = elem.getElementsByTagName(key2)[0].getAttribute("data")
            lst.append(vals)
    return retval

schema = {"forecast_information": ["city"],
          "current_conditions": ["condition", "humidity", "icon", "temp_c", "temp_f", "wind_condition"],
          "forecast_conditions": ["condition", "day_of_week", "low", "icon", "high"],
          }

url = Google_weather_url + urlencode({"weather": location})

weather_xml = urlopen(url).read()

try:
    dom = xml.dom.minidom.parseString(weather_xml)
except Exception:
    print >> sys.stderr, "Error in accessing Google Weather API. Try again a few more times"
    sys.exit(1)
    
weather_dict = xml2dict(dom, schema)

html = title_template % weather_dict["forecast_information"][0] + cur_template % weather_dict["current_conditions"][0]
for fcst in weather_dict["forecast_conditions"]:
    html += fcst_template % fcst

html += "<em>(Using the Google Weather API)</em>"

if not Lterm_cookie or options.text:
    import lxml.html
    sys.stdout.write(lxml.html.fromstring(html).text_content().encode("ascii", "ignore"))
else:
    sys.stdout.write(wrap(json.dumps(headers)+"\n\n"+html))

