"""
A lightweight CLI to monitoring tags on twitter.

Just pass your hashtag (including the hash), and you'll get
updates every 100 secs or so.
"""

import datetime
import json
import os
import pprint
import sys
import textwrap
import time
import urllib


LASTID_PATH = os.path.expanduser("~/.twitupdate")

def _saveLastId(lastId):
	with open(LASTID_PATH, "w") as f:
		f.write("%s"%lastId)


def _loadLastId():
	try:
		with open(LASTID_PATH) as f:
			return int(f.read())
	except (IndexError, ValueError):
		return 0
			

def retrieveNew(searchterm):
	"""prints new tweets 
	"""
	lastId = _loadLastId()
	f = urllib.urlopen(
		"http://twitter.com/phoenix_search.phoenix?q=%s&since_id=%s"%(
			urllib.quote(searchterm), lastId))
	try:
		stuff = f.read()
	finally:
		f.close()

	with open("zw.json", "w") as back:
		back.write(stuff)

	maxId = lastId
	tweets = json.loads(stuff)
	for t in tweets["statuses"]:
		maxId = max(maxId, t["id"])
		print ""
		print "(%s -- %s)"%(
			(t["user"]["name"] or "").encode("iso-8859-1", "ignore"), 
			(t["user"]["location"] or "").encode("iso-8859-1", "ignore"))
		print textwrap.fill(t["text"], width=70, initial_indent="  ",
			subsequent_indent="  ").encode("iso-8859-1", "ignore")

	_saveLastId(maxId)


def main():
	try:
		term = sys.argv[1]
	except IndexError:
		sys.exit("Usage: %s <twitter search term>"%sys.argv[0])

	while True:
		print "/=========== %s "%datetime.datetime.now().isoformat()
		retrieveNew(term)
		time.sleep(100)


if __name__=="__main__":
	main()

