#!/usr/bin/python
# -*- coding: utf-8

import xml.parsers.expat
import urllib
from os import execvp

ignore_elements = [
	'guid',
	'geo:lat',
	'geo:long',
	'link',
	'title',
	'ttl',
	'rss',
	'channel',
	'lastBuildDate',
	'pubDate',
	'width',
	'height',
	'item']
in_element = ""

wdata = {}
ferr = 0
icon = '/usr/share/pixmaps/gnome-question.png'
save_image_filename = "/tmp/weather-notify-temp.gif"

def start_element(name, attrs):
	global in_element, wdata
	in_element += "." + name
	if name not in ignore_elements:
		if (in_element == ".rss.channel.yweather:location"):
			wdata['city'] = attrs['city']
		elif (in_element == ".rss.channel.yweather:units"):
			wdata['units'] = attrs
		elif (in_element == ".rss.channel.yweather:wind"):
			wdata['wind'] = attrs
		elif (in_element == ".rss.channel.yweather:atmosphere"):
			wdata['atmosphere'] = attrs
		elif (in_element == ".rss.channel.yweather:astronomy"):
			wdata['astronomy'] = attrs
		elif (in_element == ".rss.channel.item.yweather:condition"):
			wdata['condition'] = attrs
		else:
			#print 'Start element:', in_element, attrs
			pass

def end_element(name):
	global in_element
	in_element = in_element[:-(name.__len__() + 1)]
	if in_element not in ignore_elements:
		#print 'End element:', in_element + "." + name
		pass

def char_data(data):
	global wdata, ferr
	if in_element not in ignore_elements:
		if (in_element == ".rss.channel.item.description"):
			for line in data.split("\n"):
				if (line != ""):
					for attr in  line.split("\""):
						if attr.count("yimg.com") > 0:
							wdata['image_url'] = attr
		elif (in_element == ".rss.channel.title" and data == "Yahoo! Weather - Error"):
			ferr = 1
		elif (data != "\n" and data != " "):
			#print 'Character data:', repr(data)
			pass

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

xwyc = """<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
 <channel>
 <title>Yahoo! Weather - Stockholm, SW</title>
 <link>http://us.rd.yahoo.com/dailynews/rss/weather/Stockholm__SW/*http://xml.weather.yahoo.com/forecast/SWXX0031_c.html</link>
 <description>Yahoo! Weather for Stockholm, SW</description>
 <language>en-us</language>
 <lastBuildDate>Sat, 25 Mar 2006 2:20 pm CET</lastBuildDate>
 <ttl>60</ttl>
 <yweather:location city="Stockholm" region="" country="SW" />
 <yweather:units temperature="C" distance="km" pressure="mb" speed="kph" />
 <yweather:wind chill="-2" direction="280" speed="16" />
 <yweather:atmosphere humidity="48" visibility="999" pressure="0" rising="0" />
  <yweather:astronomy sunrise="5:36 am" sunset="6:14 pm" />
  <image>
 <title>Yahoo! Weather</title>
 <width>142</width>
 <height>18</height>
 <link>http://weather.yahoo.com/</link>
 <url>http://us.i1.yimg.com/us.yimg.com/i/us/nws/th/main_142b.gif</url>
 </image>
 <item>
 <title>Conditions for Stockholm, SW at 2:20 pm CET</title>
  <geo:lat>59.35</geo:lat>
 <geo:long>17.95</geo:long>
  <link>http://us.rd.yahoo.com/dailynews/rss/weather/Stockholm__SW/*http://xml.weather.yahoo.com/forecast/SWXX0031_c.html</link>
 <pubDate>Sat, 25 Mar 2006 2:20 pm CET</pubDate>
 <yweather:condition text="Fair" code="34" temp="2" date="Sat, 25 Mar 2006 2:20 pm CET" />
 <description><![CDATA[
 
<img src="http://us.i1.yimg.com/us.yimg.com/i/us/we/52/34.gif" /><br />
 <b>Current Conditions:</b><br />
 Fair, 2 C<BR /><BR />
 <b>Forecast:</b><BR />
  Sat - Mostly Clear. High: 1 Low: -7<br />
  Sun - Partly Cloudy. High: 3 Low: -3<br />
 <br />
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Stockholm__SW/*http://xml.weather.yahoo.com/forecast/SWXX0031_c.html">Full Forecast at Yahoo! Weather</a><BR/>
 (provided by The Weather Channel)<br/>
 ]]></description>
 <yweather:forecast day="Sat" date="25 Mar 2006" low="-7" high="1" text="Mostly Clear" code="33" />
<yweather:forecast day="Sun" date="26 Mar 2006" low="-3" high="3" text="Partly Cloudy" code="30" />
 <guid isPermaLink="false">SWXX0031_2006_03_25_14_20_CET</guid>
 </item>
</channel>
</rss>
<!-- p2.weather.dcn.yahoo.com uncompressed Sat Mar 25 05:41:19 PST 2006 -->"""

urlfd1 = urllib.urlopen("http://xml.weather.yahoo.com/forecastrss?p=SWXX0031&u=c")
p.Parse(urlfd1.read(), 1)

#p.Parse(xwyc, 1)

if (ferr == 1):
	title = "XML fetch error"
	message = "Unable to retrieve weather information"

else:
	title = wdata['city'] + ": " + wdata['condition']['temp'] + u'°' + wdata['units']['temperature'] + " (" + wdata['condition']['text'] + ")"
	message  = "\t<b>Windspeed:</b>\t\t\t" + wdata['wind']['speed'] + " " + wdata['units']['speed'] + "\n"
	message += "\t<b>Windchill:</b>\t\t\t" + wdata['wind']['chill'] + u'°' + wdata['units']['temperature'] + "\n"
	message += "\t<b>Sunrise/Sunset:</b>\t\t" + wdata['astronomy']['sunrise'] + "/" + wdata['astronomy']['sunset'] + "\n"
	message += "\t<b>Humidity:</b>\t\t\t" + wdata['atmosphere']['humidity'] + "%\n"
	message += "\t<b>Pressure:</b>\t\t\t" + wdata['atmosphere']['pressure'] + " " + wdata['units']['pressure'] + "\n"
	message += "\t<b>Visibility:</b>\t\t\t" + wdata['atmosphere']['visibility'] + " " + wdata['units']['distance']
	urlfn, urlhdrs = urllib.urlretrieve(wdata['image_url'], save_image_filename)
	if not urlhdrs.type == "text/html":
		icon = save_image_filename

args = [
	'notify-send',
	'--icon='+icon,
	title,
	message]

execvp("notify-send", args)
