#!/usr/bin/env python
# encoding: utf-8
"""
twitcast.py

Making Twitter Talk!

Created by Henry on 2009-04-18.
Copyright (c) 2009 Thinking Ahead LLC. All rights reserved.
"""

import os
import urllib
import sys
import time
import twitter
import string
from Tkinter import *
import tkSimpleDialog

class MyDialog(tkSimpleDialog.Dialog):
  def body(self, master):
    Label(master, text="Username:").grid(row=0)
    Label(master, text="Password:").grid(row=1)
    self.e1 = Entry(master)
    self.e2 = Entry(master)
    self.e1.grid(row=0, column=1)
    self.e2.grid(row=1, column=1)
    return self.e1 # initial focus
  
  def apply(self):
    first = self.e1.get()
    second = self.e2.get()
    self.result = [first, second]


def get_tweets(user, password, count=200, tweet_id=1):
  """Gets all tweets since the id given"""
  
  # Get last tweet
  if tweet_id == 1:
    tweets = twitter.Api(user,password).GetFriendsTimeline(user,count)
  else:
  # Get tweets since (since_id)
    tweets = twitter.Api(user,password).GetFriendsTimeline(user,count,since_id=tweet_id)
    if len(tweets) == 0:
      print "No new tweets!"
      return tweet_id
  
  tweet_id = tweets[0].GetId()
  for tweet in tweets:
    user = tweet.user.name
    raw_tweet = tweet.text
    massaged_tweet = []
    split_tweet = raw_tweet.split()
    for word in split_tweet:
      if word[:4] == "http":
        massaged_tweet.append("_and a link is included")
      elif word[:2] == "RT":
        massaged_tweet.append("ReTweet")
      elif word == "hrs":
        massaged_tweet.append("hours")
      elif word == "&":
        massaged_tweet.append("and")
      else:
        massaged_tweet.append(word)
    massaged_tweet = " ".join(massaged_tweet)
    spoken_tweet =  user + " says: " + massaged_tweet.replace("|","\\_").replace("'","\\'").replace("#","hash ").replace("$","\\$").replace("(","\\'").replace(")","\\'")
    printed_tweet = user+" says: " + raw_tweet
    print printed_tweet
    print " "
    os.system('say -v Alex ' + spoken_tweet.encode('ascii'))
  return tweet_id

if __name__ == '__main__':
  tweet_id = 0
  # d = MyDialog(Tk())
  info = "Enter your username, password, and the frequency to check tweets\n New tweets will be printed AND spoken!"
  print info
  username = raw_input("Username: ") #d.result[0]
  password = raw_input("Password: ") #d.result[1]
  wait_time = raw_input("Check Twitter Every... (in sec. try 120) ")
  while 1:
    if tweet_id == 0:
      tweet_id = get_tweets(username, password, count=1)
    else:
      tweet_id = get_tweets(username, password, count=200, tweet_id=tweet_id)
    print "----"
    time.sleep(float(wait_time))

