import asyncio
from PySide.QtCore import QTimer

class EventLoop:
	loop = None

	def __init__(self):
		self.loop = asyncio.new_event_loop()
		
	def create_task(self, coro):
		self.loop.create_task(coro)
		self.update()
		
	def update(self):
		self.loop.stop()
		self.loop.run_forever()
		
	async def wait(self, time_milliseconds):
		#print("waiting " + str(time_milliseconds) + "ms...")
		currentLoop = self
		fut = self.loop.create_future()
		def callback():
			#print("wait callback")
			fut.set_result(True)
			currentLoop.update()
		QTimer.singleShot(time_milliseconds, callback)
		await fut
		#print("end wait")

main_loop = None

def get_main_loop():
	global main_loop
	if main_loop is None:
		#print("Creating main loop")
		main_loop = EventLoop()
	return main_loop