#!/bin/env python
# vim:fileencoding=iso-8859-1:ft=python
#
import hdaps, getopt, sys, threading, os, time, signal

try:
	opts, parameter = getopt.getopt(sys.argv[1:], "ds")
	opts = dict(opts)
	if len(opts) is 0:
		raise ".."
except:
	print "HDAPS command daemon"
	print "Parameters:"
	print " -s Program HDAPS command daemon"
	print " -d Run HDAPS command daemon"
	print
	print "WARNING:"
	print " This written using a really poor coding style and"
	print " should only be used for testing purposes."
	print
	sys.exit(0)

sequence = ""
exit = False
def readSequence():
	global sequence, exit
	last = time.clock()
	while 1:
		shock = myHdaps.getShock()
		now = time.clock()
		if now - last > 5:
			sequence = ""
		last = now
		if exit:
			return
		if shock is myHdaps.HIT_LEFT:
			sequence += "L"
			print "L",
			sys.stdout.flush()
		elif shock is myHdaps.HIT_RIGHT:
			sequence += "R"
			print "R",
			sys.stdout.flush()
	
myHdaps = hdaps.HDAPS()
if "-s" in opts:
	print "Enter the shock sequence now. Press <ENTER> when you're finished"
	print
	sequenceThread = threading.Thread(target=readSequence)
	sequenceThread.start()
	raw_input()
	print
	print "Put the following into ~/.hdapsCommands:"
	print "%s <command>" % sequence
	print
	print "(Hit your notebook once in case this program does not exit)"
	exit = True
	os.abort()

if "-d" in opts:
	print "Daemon mode"
	try:
		sequences = dict([ line.split(" ", 1) for line in open("%s/.hdapsCommands" % os.environ["HOME"], "r").readlines() ])
	except:
		print "Run with -s first."
		sys.exit(0)
	sequenceThread = threading.Thread(target=readSequence)
	sequenceThread.start()
	def kill(i, n):
		os.abort()
	signal.signal(2, kill)
	while 1:
		time.sleep(1)
		for trial in sequences:
			if sequence[-len(trial):] == trial:
				print "Matched %s, executing %s" % (trial, sequences[trial])
				sequence = ""
				os.system(sequences[trial])
				sequence = ""
