
from import_ import UIFLAG
import import_ as e
import vector as Vector
import event_handler
import uieditor

# initialize pygame setup
e.pygame.init()

# init the screen
e.screen = e.pygame.display.set_mode([640, 480], e.pygame.RESIZABLE)

# init the qfs
qfsInit = e.qfs.initQFS("mguns")
if (qfsInit == False):
	e.ThrowError(u"QFS Failed to Initialize: are you sure mguns folder is nearby? (either in working directory or parent)")
	exit(1)

pic1 = uieditor.uipicture(origin=(16, 16), size=(256, 128), image="gfx/menu/logo.png")
uieditor.uipicture(owner=pic1, origin=(0, 0), size=(32, 32), justify=(1, 1), anchor=(1, 1), image="F2")
uieditor.uipicture(origin=(16, 256), size=(128, 64), image="F2")

def renderRecursive(ent):
	if (ent.flags & UIFLAG.HIDE):
		return
	
	masterPosition = e.uiPosition
	if (ent.owner == e.entMaster): # screen is our parent
		masterPosition = (0, 0)
		if (ent.flags & UIFLAG.STRETCH):
			masterPosition = (0, 0)
			ent.size = e.screen.get_size()
			print(ent.image)
		elif (not Vector.Compare((0, 0), ent.anchor)):
			masterPosition = Vector.Add(masterPosition, Vector.MultS(e.screen.get_size(), ent.anchor))
	else:
		if (ent.flags & UIFLAG.STRETCH):
			masterPosition = e.uiPosition
			ent.size = ent.owner.size
		elif (not Vector.Compare((0, 0), ent.anchor)):
			masterPosition = Vector.Add(masterPosition, Vector.MultS(ent.owner.size, ent.anchor))
	masterPosition = Vector.Add(masterPosition, ent.origin)

	tsize = Vector.MultS(ent.size, ent.justify)
	masterPosition = Vector.Subtract(masterPosition, tsize)
	
	e.uiPosition = masterPosition
	ent.render()
	for lst in ent.entList:
		e.uiPosition = masterPosition
		renderRecursive(lst)
	return


e.stopExecution = False
while(e.stopExecution == False):
	# handle events
	event_handler.parse()

	# fill screen
	e.screen.fill((0, 0, 0))

	pic1.flags |= UIFLAG.HIDE
	if (round(e.time.time()) % 2 == 0):
		pic1.flags &= ~UIFLAG.HIDE

	# draw objects
	#center = e.screen.get_size()
	#center = (center[0] / 2, center[1] / 2)
	#e.pygame.draw.circle(e.screen, (0, 0, 255), (center[0], center[1] + e.math.sin(e.time.time()) * 128), 75)
	#e.entList.sort(key=lambda x: x.depth)
	#for ent in e.entList:
	#	ent.render()
	renderRecursive(e.entMaster)


	#e.pygame.draw.circle(screen, (255, 255, 255), e.mousePos, 4)

	# render screen
	e.pygame.display.flip()




