__author__ = 'Jianbin Wei'

import random
import csv
import StringIO
import urllib
from slackbot.bot import respond_to

_KNOWLEDGE = {}

@respond_to(r'^(.*) was (.*)$')
def tell_me(message, person, action):
    global _KNOWLEDGE
    person = person.lower()
    if person.lower() in _KNOWLEDGE:
        _KNOWLEDGE[person].append(action)
    else:
        _KNOWLEDGE[person] = [action]
    message.reply('Thank you for letting me know that {} is {}'.format(person, action))


@respond_to('[W|w]here is (.*)[\?]?')
def where_about(message, person):
    person = person.lower()
    actions = _KNOWLEDGE.get(person)
    if not actions:
        message.reply('I guess {} is hanging around with young girls'.format(person))
    else:
        random.seed()
        message.reply('someone told me that {} is {}'.format(person, random.choice(actions)))


@respond_to(r'stock (.*)')
def stock_price(message, stock_symbol):
    stock_info = _stock_price(stock_symbol)
    message.reply(stock_info)


def _stock_price(stock_symbol):
    stock_url = "http://finance.yahoo.com/d/quotes.csv?s={}&f=snd1l1yr".format(urllib.quote_plus(stock_symbol))
    raw_response = urllib.urlopen(stock_url).read().strip()
    response = ""
    for stock_data in csv.reader(StringIO.StringIO(raw_response)):
        response += "symbol : {} company : {} : price : ${} ".format(stock_symbol,
                                                                     stock_data[1].strip('"'),
                                                                     stock_data[3])
    return response