#!/usr/local/bin/python

"""Common functions used by googlebot.py"""

__author__ = 'avleen@gmail.com (Avleen Vig)'

import ConfigParser
import MySQLdb

def DeliverMessage(msg, irc = None, channel = None):
  """Print the message to the screen, or deliver using IRC

  Args:
    msg: string or list
    irc: IRCClient object
    channel: string
  Returns:
    None
  """
  if not msg:
    return

  if irc and type(msg) is list:
    for entry in msg:
      irc.msg(channel, entry.encode('latin-1'))
  elif irc:
    irc.msg(channel, msg.encode('latin-1'))
  elif type(msg) is list:
    print '\n'.join(msg)
  else:
    print msg

def NormalizeMessage(msg = None, irc = None, keyword = None):
  """Print the message to the screen, or deliver using IRC

  Args:
    msg: string or list
    irc: IRCClient object
    channel: string
  Returns:
    msg: string or None
  """
  if irc and msg and msg.startswith(irc.nickname):
    msg = msg.replace('%s: ' % irc.nickname, '')
  if keyword is 'default':
    return msg

  if keyword == msg:
    return None
  elif msg and keyword:
    msg = msg.replace('%s ' % keyword, '')
    return msg
  elif msg:
    try:
      msg = msg.split(' ', 1)[1]
    except IndexError:
      return msg

  if irc and msg:
    try:
      msg = msg.split(' ', 1)[1]
    except IndexError:
      return msg

  return msg


def SetupDB():
  """Sets up a new DB connection

  Args:
    None
  Returns:
    cursor: database cursor
  """
  db_config = ConfigParser.ConfigParser()
  db_config.readfp(open('config/database.conf'))
  db_unix_socket = db_config.get('database', 'db_unix_socket')
  db_username = db_config.get('database', 'db_username')
  db_password = db_config.get('database', 'db_password')
  db_name = db_config.get('database', 'db_name')
  if db_name == 'None':
    return

  db = MySQLdb.connect(unix_socket=db_unix_socket,
      user=db_username,
      passwd=db_password,
      db=db_name)
  cursor = db.cursor()
  return cursor

