from __future__ import print_function
import csv, os, sys
from datetime import datetime
from time import sleep
import OSC


# open a connection to pd
client = OSC.OSCClient()
address = '127.0.0.1', 4000 # 57120==SC
client.connect( address ) # set the address for all following messages
print ("1.client stderr", file=sys.stderr)


msg = OSC.OSCMessage() # OSCresponder name: '/touch'
msg.setAddress("/twitter-ikstem")
#msg.append('hello from python')
#client.send(msg)

os.system('xzcat /media/floppy/twittersonification.csv.xz > /tmp/twittersonification.csv') #floppydisk
#os.system('xzcat twittersonification.csv.xz > /tmp/twittersonification.csv') #lokaal



then = None
with open('/tmp/twittersonification.csv', 'rU') as csvfile:
	file = csv.DictReader(csvfile)
	print ("2.opening file stderr", file=sys.stderr)

	#csv.DictReader(csvfile)(["time"] + ['time'])
	i=0
	sleep_time=1
	for row in file:
		print ("3.row stderr", file=sys.stderr)

		i+=1
		t = row['time']
		print ("4.time stderr", file=sys.stderr)
		t = float(t)
		now = datetime.fromtimestamp(t) #[]dictreader reads the rowheader
		#print now, row
		if then:
			ti = (now-then).total_seconds()
			#print ti/100
			sleep_time = ti/40
			print ("5.msg stderr", file=sys.stderr)


		#msg.append( row['text'].lower() )
 		#client.send(msg)
 		#msg.clearData()	

		if "#ikstem" in row['text'].lower()	and '#gestemd' in row['text'].lower():
			msg.append( ['both', str(now)] )
		elif '#ikstem' in row['text'].lower():
			msg.append( ['#ikstem', str(now) ])
		elif '#gestemd' in row['text'].lower():
			msg.append( ['#gestemd', str(now)] )
		
		#	msg.append( [ str(row['text']) ] )
	
		# send an osc message to pd
		#print  msg#[ i, row['text'], str(now)]
 		sleep(sleep_time)	
 		client.send(msg)
 		msg.clearData()
 		then = now
 		print ("6.last print stderr", file=sys.stderr)
