#!/usr/local/bin/pyhton

from feedparser import parse
import MySQLdb
import re

def WeatherLookup(location):
  """Lookup the weather from rssweather.com

  The location input can be in a variety of formats. We determine what kind of
  input we're looking and then craft the correct feed URL from that.

  Args:
    location: str (5 dting US zip code, 'country, city' or 3 letter IATA code.

  Returns:
    string: Either the weather report, or an error message to print.
  """

  location = location.replace('weather ', '')
  zip_p = re.compile('^[\d+]{5}$')
  airport_p = re.compile('^[\w]{3}$')
  icao_p = re.compile('^[\w]{4}$')
  city_p = re.compile('^([\w]+),\s+([\w]+)$')

  if zip_p.match(location):
    feed = 'http://www.rssweather.com/rss.php?zipcode=%s' % location
  elif airport_p.match(location):
    selectsql = """SELECT icao FROM googlebot_airports
        WHERE iata = '%s'""" % location
    icao = MysqlLookup(selectsql)
    if icao == None:
      return 'Unknown airport'
    feed = 'http://www.rssweather.com/icao/%s/rss.php' % icao
  elif icao_p.match(location):
    feed = 'http://www.rssweather.com/icao/%s/rss.php' % location
  elif city_p.match(location):
    city = city_p.match(location).group(1)
    country = city_p.match(location).group(2)
    selectsql = """SELECT icao FROM googlebot_airports
        WHERE city = '%s'
        AND country = '%s' LIMIT 1""" % (city, country)
    icao = MysqlLookup(selectsql)
    if icao == None:
      return 'Unknown city and country combination'
    feed = 'http://www.rssweather.com/icao/%s/rss.php' % icao
  else:
    return 'No matching regular expressions for your input: %s' % location
  weather = parse(feed)
  try:
    result = weather.entries[0].title
  except IndexError:
    return 'No weather available for this location at this time'
  else:
    return result

def MysqlLookup(selectsql):
  """Connect to the database and lookup the ICAO code for the location.

  Args:
    selectsql: str (SQL SELECT string)

  Returns:
    string: ICAO code or None
  """

  db = MySQLdb.connect(unix_socket='/tmp/mysql.sock',
      user='silverwraith',
      passwd='f00dlecarpw33d',
      db='silverwraith')
  cursor = db.cursor()
  cursor.execute(selectsql)
  numrows = int(cursor.rowcount)
  if numrows == 1:
    row = cursor.fetchone()
    location = row[0]
    return location
  else:
    return None

if __name__ == '__main__':
  import sys
  result = WeatherLookup(sys.argv[1])
  print result.encode('latin-1')
