#!/usr/local/bin/pyhton

import common
import datetime
import imp
import re
import sys
import Quote

module_triggers = ['quote']


def Gather(keyword, msg = None, 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 == 'quote':
    result = GetQuote(msg)
  common.DeliverMessage(result, irc, channel)


def GetQuote(symbol):
  """Get quotes from finance.yahoo.com
  
  Args:
    msg: string

  Returns:
    str: Success or failure message
  """
  if re.compile('([\^A-Z]+$)').search(symbol):
    try:
      quote = Quote.Lookup(symbol)
    except ValueError:
      result = ['Quote data not available for: %s' % symbol]
    else:
      quotedate = datetime.datetime.fromtimestamp(quote.time)
      result = ['At %s, the value of %s was USD%.2f' % \
                (quotedate, symbol, quote.value),
                'Today\'s high: %.2f, today\'s low: %.2f.'
                'Change since last market opening: %.2f.' % \
                (quote.high, quote.low, quote.change)]
  else:
    result = 'No symbols matching: %s' % symbol

  return result


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()

