import urllib
import re, sys

from etm.rc import *
from xml.etree.ElementTree import ElementTree

y_regex = re.compile(r'\{.*\}units$')

def direction(deg):
    points = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
    index = (int(deg)*100+1125)/2250
    if index == 16:
        return points[0]
    else:
        return points[index]

def getweather():
    ret = []
    url = 'http://xml.weather.yahoo.com/forecastrss?p=%s' % weatherlocation
    tree = ElementTree()
    try:
        tree.parse(urllib.urlopen(url))
        channel = tree.find("channel")
        data = {}
        if not channel is None:
            elements = channel.getchildren()
            for element in elements:
                if not element is None:
                    m = y_regex.match(element.tag)
                    if m:
                        group = 'units:'
                    else:
                        group = ''
                    items = element.items()
                    for item in items:
                        if item[0] in ['city', 'region', 'country', 'temperature',
                            'distance', 'pressure', 'speed', 'direction', 'chill',
                             'pressure', 'rising', 'visibility', 'humidity',
                             'sunrise', 'sunset']:
                                data["%s%s" % (group, item[0])] = item[1]
    except:
        return ['Network problem - could not obtain Yahoo weather data.']
    title = "%s %s" % (weather, data['city'])
    if data['region']:
        title += ", %s" % data['region']
    elif data['country']:
        title += ", %s" % data['country']
    channelitem = tree.find("channel/item")
    if not channelitem is None:
        elements = channelitem.getchildren()
        first = True
        second = False
        temperature = 0
        for element in elements:
            if not element is None:
                items = element.items()
                hash = {}
                string = ""
                for item in items:
                    if item[0] in ['day', 'date', 'text', 'temp', 'high', 'low']:
                        hash[item[0]] = item[1]
                        if item[0] == 'temp':
                            temperature = item[1]
                if hash:
                    if first:
                        ret.append(title)
                        ret.append("    %s: %s" %
                            (current_conditions, hash['date']))
                        keys = ['text', 'temp']
                        first = False
                        second = True
                    elif second:
                        keys = ['day', 'date', 'text', 'temp']
                        string = "        wind "
                        if data['speed'] and float(data['speed']) > 0:
                            for key in ['direction', 'speed', 'chill']:
                                if key in data:
                                    if key == 'direction':
                                        string += "%s, " % (
                                            direction(data[key]))
                                    elif key == 'chill' and \
                                        data['chill'] != temperature:
                                        string += ", %s %s %s" % (
                                            chill,
                                            data['chill'],
                                            data['units:temperature'])
                                    elif key == 'speed':
                                        string += "%s %s %s" % (
                                            key,
                                            data[key],
                                            data['units:speed'])
                        else:
                            string += "calm"
                        ret.append(string)
                        string = "        "
                        for key in ['humidity', 'visibility', 'pressure',
                            'rising']:
                            if key in data:
                                if key == 'pressure':
                                    string += "%s %s %s, " % (
                                        key,
                                        data[key],
                                        data['units:pressure'])
                                elif key == 'visibility':
                                    string += "%s %s %s, " % (
                                        key,
                                        data[key],
                                        data['units:distance'])
                                elif key == 'rising':
                                    if data['rising'] == '1':
                                        string += rising
                                    elif data['rising'] == '-1':
                                        string += falling
                                    else:
                                        string += constant
                                else:
                                    string += "%s %s, " % (key, data[key])
                        ret.append(string)
                        string = "        "
                        for key in ['sunrise', 'sunset']:
                            if key in data:
                                if key == 'sunrise':
                                    string += "%s %s, " % (key, data[key])
                                else:
                                    string += "%s %s" % (key, data[key])
                        ret.append(string)
                        ret.append("    %s" % forecast)
                        second = False
                    string = "        "
                    for key in keys:
                        if key in hash:
                            if key == 'day':
                                string += "%s, " % hash[key]
                            elif key == 'date':
                                string += "%s: " % hash[key]
                            elif key == 'temp':
                                string += "%s %s" % (
                                    hash[key], data['units:temperature'])
                            else:
                                string += "%s, " % hash[key]
                    for key in ['high', 'low']:
                        if key in hash:
                            if key == 'high':
                                string += "%s %s %s, " % (
                                    key,
                                    hash[key],
                                    data['units:temperature'])
                            elif key == 'low':
                                string += "%s %s %s" % (
                                    key,
                                    hash[key],
                                    data['units:temperature'])
                    ret.append(string)
    return ret

if __name__ == "__main__":
    # http://xml.weather.yahoo.com/forecastrss?p=USNC0105&u=f
    # http://xml.weather.yahoo.com/forecastrss?p=USNC0105hr&u=f
    # weatherlocation = 'USNC0105&u=f' # Chapel Hill
    # location = 'USNC0105&u=c' # Chapel Hill celcius
    # location = 'FRXX2071&u=c' # Paris
    # location = 'UKXX1822&u=f' # London
    # location = 'GMXX0008&u=c' # Berlin
    l = getweather()
    print "\n".join(l)