#!/usr/local/bin/pyhton

import common
import imp
import re
import sys
from feedparser import parse

module_triggers = ['weather']

def Gather(keyword, msg, irc = None, channel = None):
  module_location = imp.find_module('common')
  module = imp.load_module('common', *module_location)
  msg = common.NormalizeMessage(msg,irc, keyword)
  if keyword == 'weather':
    result = WeatherLookup(msg)
  result = result.encode('latin-1')
  common.DeliverMessage(result, irc, channel)


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
  """
  cursor = common.SetupDB()
  cursor.execute(selectsql)
  numrows = int(cursor.rowcount)
  if numrows == 1:
    row = cursor.fetchone()
    location = row[0]
    return location
  else:
    return None


def main():
  try:
    keyword = sys.argv[1]
  except IndexError:
    sys.exit(1)
  try:
    argument = sys.argv[2]
  except IndexError:
    sys.exit(1)

  if keyword in module_triggers:
    Gather(keyword, argument)

if __name__ == '__main__':
  main()

