#!/usr/bin/env python
'''
PWT is a simple command line twitter client

Copyright 2008 Eric Stein
License: GPL2/GPL3, at your option.  For details see LICENSE.

$Id: pwt 8 2010-01-04 01:32:53Z eastein $
'''

import time
import os
import os.path
import sys
import urllib2
import twitter

def getApi() :
	fn = os.path.join(os.path.expanduser('~'), '.pwt')
	if os.path.exists(fn) :
		lns = file(fn).read().split('\n')
	
		if len(lns) < 2 :
			print 'Invalid formatting.  Expected username on first line and password on the next'
			sys.exit(1)

		return twitter.Api(lns[0], lns[1])

if __name__ == '__main__':
	api = getApi()

	if not api :
		print 'Write your twitter username and password on two separate lines to ~/.pwt'
		sys.exit(1)

	try:
		if len(sys.argv) < 2 :
			print 'Usage: pwt [message|-l]'
			sys.exit(2)

		if sys.argv[1] == '-l' :
			s=api.GetFriendsTimeline()

			for u in s :
				ts = time.strftime('%Y%m%d %H:%M:%S', time.localtime(u.created_at_in_seconds))
				print '[%s] <%s> %s' % (ts, u.user.name, u.text)	
		else :
			message = sys.argv[1]
			for i in range(2, len(sys.argv)) :
				message += ' ' + sys.argv[i]

			api.PostUpdate(message)
			print 'updated'

	except urllib2.HTTPError :
		print 'authorization failure'
		sys.exit(3)
