from urllib2 import Request, urlopen, URLError
import re, sys

from etm.etmRC import *
from xml.etree.ElementTree import ElementTree, tostring

import socket
timeout = 10
socket.setdefaulttimeout(timeout)

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 = []
    frcst = []
    url = 'http://xml.weather.yahoo.com/forecastrss?p=%s' \
            % weatherlocation
    req = Request(url)
    try:
        response = urlopen(req)
    except URLError, e:
        if hasattr(e, 'reason'):
            msg = """\
We failed to reach the weather server at 
    %s
Reason: %s.""" % (url, e.reason)
        elif hasattr(e, 'code'):
            msg = """\
The weather server at 
    %s 
couldn\'t fulfill the request.
Error code: %s.""" % (url, e.code)
        return(0, msg)

    # connection is fine
    tree = ElementTree()
    response = urlopen(req)
    tree.parse(response)
    channel = tree.find("channel")
    data = {}
    if not channel is None:
        elements = channel.getchildren()
        # elements = tree.list(channel)
        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]
    title = "%s %s" % (weather, data['city'])
    if data['region']:
        title += ", %s" % data['region']
    elif data['country']:
        title += ", %s" % data['country']
    channelitem = channel.find("item")
    # channelitem = tree.getroot()
    if channelitem is not None: 
        elements = channelitem.getchildren()
        first = True
        second = False
        temperature = 0
        for element in elements:
            if element is not 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)
                        #### Forecast ####
                        ret.append("    %s" % forecast)
                        second = False
                    string = "        "
                    fst = ""
                    for key in keys:  # keys = ['day', 'date', 'text', 'temp']
                        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'])
                                fst += "%s%s" % (
                                    hash[key], data['units:temperature'])
                            else:
                                string += "%s, " % hash[key]
                                fst += "%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'])
                                fst += "%s %s%s, " % (
                                    key,
                                    hash[key],
                                    data['units:temperature'])
                            elif key == 'low':
                                string += "%s %s%s" % (
                                    key,
                                    hash[key],
                                    data['units:temperature'])
                                fst += "%s %s%s" % (
                                    key,
                                    hash[key],
                                    data['units:temperature'])
                    ret.append(string)
                    frcst.append(fst)
    return(1,ret)


def getForecast():
    f = []
    ok, l = getWeather()
    if ok:
        f.append(l[1].strip().split('s: ')[1])
        f.append(l[2].strip())
        for i in [-2, -1]:
            f.append(l[i].split(':')[1].strip())
    else:
        f = l
    return(ok, f)


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
    ok, l = getWeather()
    if ok:
        print "\n".join(l)
    else:
        print l
    ok, l = getForecast()
    if ok:
        print "\n".join(l)
    else:
        print l