#!/usr/bin/env python
import sys
import getopt
import urllib2
from xml.dom import minidom

WEATHER_URL_ZIP = 'http://xml.weather.yahoo.com/forecastrss?p=%s&u=%s'
WEATHER_URL_WOEID = 'http://xml.weather.yahoo.com/forecastrss?w=%s&u=%s'
WEATHER_NS = 'http://xml.weather.yahoo.com/ns/rss/1.0'

# Portions of this function borrowed from Yahoo's developer page.
# http://developer.yahoo.com/python/python-xml.html
def getWeather(location, locationtype, units):
	if locationtype == 'zip':
		url = WEATHER_URL_ZIP % (location,units)
		dom = minidom.parse(urllib2.urlopen(url))
		forecasts = []
	
	elif locationtype == 'woeid':
		url = WEATHER_URL_WOEID % (location,units)
		dom = minidom.parse(urllib2.urlopen(url))
		forecasts = []
				
	else:
		print "Not a valid location code"
		return 0

	for node in dom.getElementsByTagNameNS(WEATHER_NS, 'forecast'):
		forecasts.append({
			'date': node.getAttribute('date'),
			'low': node.getAttribute('low'),
			'high': node.getAttribute('high'),
			'condition': node.getAttribute('text')
		})
	conditions = dom.getElementsByTagNameNS(WEATHER_NS, 'condition')[0]
	return {
		'current_condition': conditions.getAttribute('text'),
		'current_temp': conditions.getAttribute('temp'),
		'forecasts': forecasts,
	        'title': dom.getElementsByTagName('title')[0].firstChild.data
	}

def printForecast(forecasts, units):
	
	print("\nExtended Forecast: \n")
	for day in forecasts:
		for item in day:
			if item == "high":
				print "High" + '\t' + day[item] + units.upper()
			elif item == "low":
				print "Low" + '\t' + day[item] + units.upper()
			elif item == "condition":
				print day[item] + '\n'
			else:
				print day[item]	


def usage():
	print ("Usage: weather -[z,w] -[c,f] -e (optional) <zipcode || woeid>")
	print ("-[z.w] : use ZipCode (z) or WOEID (w)")
	print ("-[c,f] : units Celcius (c default) or Fahrenheit (f) ")
	print ("-e : print extended forcast information ")
	


def main():
	try:
		units='c'
		extendedforecast=False

		opts, args = getopt.getopt(sys.argv[1:], "hezwcf", ["help", "halp", "location"])
		if not opts:
			print ("No options supplied")
			usage()
			sys.exit(2)

		for opt, arg in opts:
			if opt in ("-h", "--help", "--halp"):
				usage()
				sys.exit(2)
			elif opt == "-c":
				units='c'
			elif opt == "-f":
				units='f'
			elif opt == "-z":
				locationtype="zip"
			elif opt == "-w":
				locationtype="woeid"
			elif opt == "-e":
				extendedforecast=True
			else:
				print ("Unknown option.")
				usage()
				sys.exit(2)
		if not args:
			print ("No location specified")
			usage()
			sys.exit(2)
		else:
			location=args[0]

		current_conditions = getWeather(location, locationtype, units)
		forecasts = current_conditions['forecasts']

		print (current_conditions['title'])
		print ("Currently %s%s%s and %s"  %  (current_conditions['current_temp'],unichr(176),units.upper(),current_conditions['current_condition']))
		if extendedforecast is True:
			printForecast(forecasts, units)
		
	except getopt.GetoptError,e:
		print e
		usage()
		sys.exit(3)

if __name__ == "__main__":
	main()
