#!/usr/local/bin/python

""" Grab a random grouphug string """

__author__ = 'Avleen Vig <work@silverwraith.com'

import HTMLParser
import common
import imp
import re
import sys
import urllib

module_triggers = ['grouphug']


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 == 'grouphug':
    result = GrouphugLookup(msg)
  common.DeliverMessage(result, irc, channel)


class MLStripper(HTMLParser.HTMLParser):
  def __init__(self):
    self.reset()
    self.fed = []
  def handle_data(self, d):
    self.fed.append(d)
  def get_fed_data(self):
    return ''.join(self.fed)


def GrouphugLookup(confession = None):
  if confession:
    url = 'http://grouphug.us/confessions/%s' % confession
  else:
    url = 'http://grouphug.us/random'
  html = urllib.urlopen(url).read()
  pattern = '.*([\d]{9}).*<td class="conf-text">(.*?)</td>'
  confession_p = re.compile(pattern, re.DOTALL)
  confession_html = '%s: %s' % (confession_p.match(html).group(1),
      confession_p.match(html).group(2))
  stripper = MLStripper()
  stripper.feed(confession_html)
  confession_text = stripper.get_fed_data()
  formatted_confession_text = re.sub("([\n\t\s]+)", " ", confession_text)
  return formatted_confession_text


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

  if keyword in module_triggers:
    Gather(keyword, argument)

if __name__ == '__main__':
  main()

