"""Weather module for ppbot.
@package ppbot

Given a zipcode, will lookup the associated weather for that zipcode.
Will be using wunderground.com's API.

@syntax w <zipcode>

"""
import urllib
import string
import re
import json

import requests

from config import BotConfig
from modules import *


class Weather(Module):
    API_URL = 'http://api.wunderground.com/api/%s/conditions/q/%s.json'

    def __init__(self, *args, **kwargs):
        """Constructor"""

        Module.__init__(self, kwargs=kwargs)

        # TODO throw exception if it doesn't exist
        self.api_key = BotConfig().get('wunderground', 'api_key')
        # url for wunderground's api, forecast url

    def _register_events(self):
        """Register module commands."""

        self.add_command('w')

    def w(self, event):
        """Action to react/respond to user calls."""

        if self.num_args >= 1:
            # need to fetch the weather and parse it
            zipcode = ' '.join(event['args'])

            m = re.search('\+\+|\-\-', zipcode)
            if m:
                self.msg(event['target'], 'Could not get weather data for "%s--"' % event['nick'])
            else:
                try:
                    weather = self.get_weather(zipcode)
                    # stylize the message output
                    message1 = "%(city)s (%(zipcode)s) - %(condition)s @ %(temp_f)sF (%(temp_c)sC) - Humidity: %(humidity)s, Winds: %(wind)s" % (weather)
                    #message2 = "Today (%(day)s) - High: %(high)sF, Low: %(low)sF - %(condition)s" % weather['forecast'][0]
                    #message3 = "Tomorrow (%(day)s) - High: %(high)sF, Low: %(low)sF - %(condition)s" % weather['forecast'][1]
                    # send the messages
                    self.msg(event['target'], message1)
                    #self.msg(event['target'], message2)
                    #self.msg(event['target'], message3)
                except:
                    import traceback
                    traceback.print_exc()
                    self.msg(event['target'], 'Could not get weather data for "%s"' % zipcode)
        else:
            self.syntax_message(event['nick'], '.w <zipcode>')

    def get_weather(self, zipcode):
        """Connects to weather API and parses for the weather."""

        # make the parser, and send the xml to be parsed
        data = {}
        r = requests.get(self.__class__.API_URL % (self.api_key, urllib.quote_plus(zipcode)))
        resp = json.loads(r.text)
        obs = resp['current_observation']

        data['city'] = obs['display_location']['full']
        data['zipcode'] = obs['display_location']['zip']
        data['temp_f'] = obs['temp_f']
        data['temp_c'] = obs['temp_c']
        data['condition'] = obs['weather']
        data['humidity'] = obs['relative_humidity']
        data['wind'] = obs['wind_string']
        return data

@@ -1294,16 +1294,45 @@
  output%0A
+                    try:%0A    
         
@@ -1477,16 +1477,189 @@
 eather)%0A
+                    except:%0A                        message1 = %22%25(city)s - %25(condition)s @ %25(temp_f)sF (%25(temp_c)sC) - Humidity: %25(humidity)s, Winds: %25(wind)s%22 %25 (weather)%0A%0A
         
@@ -2634,33 +2634,32 @@
 ey, 
-urllib.quote_plus(zipcode
+zipcode.replace(' ', '_'
 )))%0A
@@ -2692,16 +2692,33 @@
 r.text)%0A
+        try:%0A    
         
@@ -2756,24 +2756,28 @@
 '%5D%0A%0A        
+    
 data%5B'city'%5D
@@ -2811,16 +2811,20 @@
 'full'%5D%0A
+    
         
@@ -2872,32 +2872,36 @@
 %5B'zip'%5D%0A        
+ 
+   
 data%5B'temp_f'%5D =
@@ -2915,16 +2915,20 @@
 emp_f'%5D%0A
+    
         
@@ -2962,24 +2962,28 @@
 c'%5D%0A        
+ 
+   
 data%5B'condit
@@ -3005,16 +3005,20 @@
 ather'%5D%0A
+    
         
@@ -3065,24 +3065,28 @@
 y'%5D%0A        
+  
+  
 data%5B'wind'%5D
@@ -3107,16 +3107,21 @@
 tring'%5D%0A
+%0A    
         
@@ -3132,8 +3132,91 @@
 rn data%0A
+        except KeyError:%0A            print 'no current_obs'%0A            print resp%0A

Add some error checking for weather module