#!/usr/bin/env python

import pythoncom
import win32event
import win32gui
import win32con

class WindowsMessageLoop(object):
	def pump_waiting_messages(self):
		#win32gui.PumpWaitingMessages()
		#return
		#pythoncom.PumpWaitingMessages()
		while True:
			B_found_message_1, message_1 = win32gui.PeekMessage(0, 0, 0, win32con.PM_REMOVE)
			if not B_found_message_1:
				break
			#B_found_message_1, message_1 = win32gui.GetMessage(0, 0, 0)
			if B_found_message_1:
				print "MSG", message_1
				win32gui.TranslateMessage(message_1)
				win32gui.DispatchMessage(message_1)
				print "AFTER DISPATCH"
			else:
				print "NO MSG"
		print "DONE1"
			

	# TODO GetMessage.

windows_message_loop = WindowsMessageLoop()

def select(handles, timeout = win32event.INFINITE):
	"""
	tries to do something like UNIX select() would do, i.e. wait until something interesting happens.
	"Something interesting" can be:
	1) A Windows Message arrived: windows_message_loop is returned.
	2) An event was signalled: the event is returned.
		the following handle types work:
			- change notification.
			- console input.
			- event.
			- memory resource notification.
			- mutex.
			- process.
			- semaphore.
			- thread.
			- waitable timer.
	"""
	global windows_message_loop
	assert(len(handles) < 256) # and a list.
	status = win32event.MsgWaitForMultipleObjects([handle.handle if hasattr(handle, "handle") else handle for handle in handles], False, timeout, win32event.QS_ALLEVENTS)
	if status == win32event.WAIT_TIMEOUT:
		return None # ???
	elif status == win32event.WAIT_OBJECT_0 + len(handles): # a windows message is there.
		return windows_message_loop
	elif status >= win32event.WAIT_OBJECT_0 and status < win32event.WAIT_OBJECT_0 + len(handles):
		# an event actually signalled.
		return handles[status - win32event.WAIT_OBJECT_0]
	# TODO elif status >= win32event.WAIT_ABANDONED_0 and status < win32event.WAIT_ABANDONED_0 + len(handles):
	# TODO elif status == WAIT_FAILED:
	else:
		# TODO throw proper exception?? seems to happen automagically: pywintypes.error: (6, 'MsgWaitForMultipleObjects', 'The handle is invalid.')
		return None # FIXME raise GetLastError()



