from pygame import *

Font = None
LastKey = None

class dummysound:
    def play(self): pass

def load_sound(file):
    if not mixer: return dummysound()
    try:
        sound = mixer.Sound(file)
        return sound
    except error:
        print 'Warning! Unable to load:', file
    return dummysound()

class sounds:
	def __init__ (self):
		self.soundarray = {}

	def play(self, filename):
		if (filename in self.soundarray):
			self.soundarray[filename].play()

	def addsound(self, filename):
		if not (filename in self.soundarray):
			self.soundarray[filename] = load_sound(filename)


def addtxt(txt, txtlist, color = (50, 200, 50)):
	img = Font.render(txt, 1, color, (0, 0, 0))
	txtlist.append(img)
	

def drawtxtlist(win, txtlist, title = "Trigger List"):
	win.blit(Font.render(title, 1, (155, 155, 155), (0,0,0)), (2, 132))
	ypos = 450
	h = list(txtlist)
	h.reverse()
	for line in h:
		r = win.blit(line, (10, ypos))
		win.fill(0, (r.right, r.top, 620, r.height))
		ypos -= Font.get_height()


def main():
	init()

	win = display.set_mode((640, 480))
	display.set_caption("pyTrigger")

	global Font
	Font = font.Font(None, 26)

		# text list to be displayed
	txtlist = []

		# detect and init joysticks
	for x in range(joystick.get_count()):
		j = joystick.Joystick(x)
		j.init()
		addtxt('Joystick found: %s (Joy %s)' % (j.get_name(), j.get_id()), txtlist)

	if not joystick.get_count():
		addtxt('No Joysticks found', txtlist)

		# Dictionary of sound objects, referenced by filname
	soundarray = sounds()

		# Dictionary of the number of the next sound to be played, referenced by button
	next_sound = {}

		# Dictionary of buttons, scenes and sounds
	playlists = {}

		# List of scene buttons
	scene_buttons = []

		# Read and insert playlist items

	scene = 0
	button = ""

		# Parse playlistfile
	f = open('playlists.txt', 'r')
	for line in f:
		line = line.strip()
		if line:
				# Scene header
			if line[0] == "#":
				scene = scene + 1
#				print scene

				# Button header
			elif line[0] == ":":
				button = line[1:-1]
#				print button
					# Scene button
				if scene == 0:
					scene_buttons.append(button)
				else:
						# Play button
					if not button in playlists:
						playlists[button] = {}
					if not scene in playlists[button]:
						playlists[button][scene] = []

					next_sound[button] = 0

				# Options
			elif line[0] == "~":
					# Loop
				if line[1:-1] == 'loop':
					if not 'loop' in playlists[button]:
						playlists[button]['loop'] = []				
					playlists[button]['loop'].append(scene)

				# Append sound name and load sound to soundarray
			else:
				playlists[button][scene].append(line)
#				print playlists[button][scene]
				soundarray.addsound(line)

#	print playlists	

		# main loop
	event.set_grab(0)
	trigger_key = ""
	redraw = 1
	scene = 1

	while 1:

		for e in event.get():

			trigger_key = ""

			if e.type == QUIT:
				return

			if e.type == KEYDOWN:
				trigger_key = "Key %s" % e.key
				addtxt('Key %s (%s)' % (e.key, key.name(e.key)),txtlist)
				redraw = 1
			elif e.type == MOUSEBUTTONDOWN:
				trigger_key = "Mouse %s" % (e.button)
				addtxt(trigger_key, txtlist)
				redraw = 1
			elif e.type == JOYBUTTONDOWN:
				trigger_key = "Joy %s %s" % (e.joy, e.button)
				addtxt(trigger_key, txtlist)
				redraw = 1
			elif e.type == JOYAXISMOTION:
				if e.axis == 0 and e.value > 0.9:
					trigger_key = "Joy %s Right" % (e.joy)
				if e.axis == 0 and e.value < -0.9:
					trigger_key = "Joy %s Left" % (e.joy)
				if e.axis == 1 and e.value > 0.9:
					trigger_key = "Joy %s Down" % (e.joy)
				if e.axis == 1 and e.value < -0.9:
					trigger_key = "Joy %s Up" % (e.joy)
				addtxt(trigger_key, txtlist)
				redraw = 1

				# Next scene
			if trigger_key in scene_buttons:
				scene = scene + 1
				for i in next_sound:
					next_sound[i] = 0
				addtxt("Scene change: %i" % (scene), txtlist, (200, 50, 50))

				# Play sound
			elif trigger_key in playlists and scene in playlists[trigger_key]:

					# Loop
				if next_sound[trigger_key] == len(playlists[trigger_key][scene]):
					if 'loop' in playlists[trigger_key]:
						if scene in playlists[trigger_key]['loop']:
							next_sound[trigger_key] = 0

					# Play
				if next_sound[trigger_key] < len(playlists[trigger_key][scene]):
					text = "%i:%i - %s" % (scene, next_sound[trigger_key], playlists[trigger_key][scene][next_sound[trigger_key]])

					addtxt(text, txtlist, (200, 50, 50))
					soundarray.play(playlists[trigger_key][scene][next_sound[trigger_key]])
					next_sound[trigger_key] = next_sound[trigger_key] + 1

			# Print all events
#		addtxt('%s: %s' % (event.event_name(e.type), e.dict),txtlist)

		if redraw:		
			txtlist = txtlist[-13:]
			drawtxtlist(win, txtlist, "Trigger List - Scene %i" % (scene))
			display.flip()
			time.wait(10)
			redraw = 0

if __name__ == '__main__': main()