
import import_ as e
from import_ import UIFLAG
import vector as Vector
import uieditor
from pyglet.gl import *

global cursor
global cursorindex
global entityviewer_size
cursor = (0, 0)
cursorindex = 0
entityviewer_size = 0
buttonLocations = []
renderShapes = []
imageasset = {}
imageasset["arrow_down"] = e.pyglet.image.load("gfx/arrow_down.png")
imageasset["arrow_up"] = e.pyglet.image.load("gfx/arrow_up.png")
imageasset["arrow_left"] = e.pyglet.image.load("gfx/arrow_left.png")
imageasset["arrow_right"] = e.pyglet.image.load("gfx/arrow_right.png")
imageasset["hide"] = e.pyglet.image.load("gfx/hide.png")

class buttonLocation():
	def __init__(self, x, y):
		self.x = x
		self.y = y
		self.width = 1024
		self.height = 22

class buttonEntity(buttonLocation):
	def __init__(self, x, y, ent=None):
		if (ent == None):
			del self
			return
		super().__init__(x, y)
		self.ent = ent

class buttonEntParameter(buttonLocation):
	def __init__(self, x, y, width, height, parameter):
		super().__init__(x, y)
		self.width = width
		self.height = height
		self.parameter = parameter

batch = e.pyglet.graphics.Batch()

def recurseDropdown(ent):
	for lst in ent.entList:
		if (lst == e.getuiElementSelected() or lst == e.uiElementHover):
			return True
		if (recurseDropdown(lst) == True):
			return True
	return False

def recurseList(ent):
	global cursor
	global cursorindex
	
	dropped_down = (ent.flags & UIFLAG.DROPDOWN)
	if (not dropped_down):
		dropped_down = recurseDropdown(ent)

	if (ent != e.entMaster):
		color = (60, 60, 60, 110) if cursorindex % 2 == 0 else (50, 50, 50, 110)
		if (ent == e.getuiElementSelected()):
			color = Vector.Add4(color, (40, 0, 0, 20))
		elif (ent == e.getuiElementHover()):
			color = Vector.Add4(color, (15, 15, 15, 30))

		renderShapes.append(e.pyglet.shapes.Rectangle(cursor[0], cursor[1] - 22, 1024, 22, color, batch=batch))
		buttonLocations.append(buttonEntity(cursor[0], cursor[1] - 22, ent))

		xoff = 2
		if (ent.entList):
			arrow_sprite = e.pyglet.sprite.Sprite(imageasset["arrow_down"] if (dropped_down) else imageasset["arrow_right"], cursor[0] + xoff, cursor[1] - 19, batch=batch)
			arrow_sprite.width = 15
			arrow_sprite.height = 15
			renderShapes.append(arrow_sprite)
			xoff += 16
		xoff += 4
		if (ent.flags & UIFLAG.HIDE):
			arrow_sprite = e.pyglet.sprite.Sprite(imageasset["hide"], cursor[0] + xoff, cursor[1] - 19, batch=batch)
			arrow_sprite.width = 15
			arrow_sprite.height = 15
			renderShapes.append(arrow_sprite)
			xoff += 20
		
		strname = ent.__class__.__name__
		if (ent.__class__ == uieditor.uipicture):
			imgname = ent.image
			if (len(imgname) > 16):
				imgname = imgname.split("/")[-1]
			strname += ": " + imgname

		renderShapes.append(e.pyglet.text.Label(strname, "Consolas", 10, x=cursor[0] + xoff, y=cursor[1] - 9, anchor_y='center', batch=batch))

		cursorindex += 1
		cursor = Vector.Add(cursor, (32, -22))
		if (cursor[0] > e.toolbar_windowSize[0] * 0.8):
			cursor = (e.toolbar_windowSize[0] * 0.8, cursor[1])

	if (ent == e.entMaster or dropped_down):
		holdpos = cursor
		for lst in ent.entList:
			cursor = (holdpos[0], cursor[1])
			recurseList(lst)
			if (ent == e.entMaster):
				cursor = Vector.Add(cursor, (0, -4))

entityviewer_info = {}

global proplist
proplist = []

def entityviewer_generateinfo():
	global proplist
	entityviewer_info.clear()
	ent = e.getuiElementSelected()
	if (ent == None):
		return
	
	for prop in proplist:
		if (prop.ftype == tuple):
			entityviewer_info[prop.name + "_x"] = ent.__dict__[prop.name][0]
			entityviewer_info[prop.name + "_y"] = ent.__dict__[prop.name][1]
		else:
			entityviewer_info[prop.name] = ent.__dict__[prop.name]

def entityviewer_box(org, sz, param):

	if (sz[0] > e.toolbar_windowSize[0] - (16 + org[0])):
		sz = (e.toolbar_windowSize[0] - (16 + org[0]), sz[1])

	renderShapes.append(e.pyglet.shapes.Rectangle(org[0], org[1], sz[0], sz[1], (110, 110, 110, 255), batch=batch))
	renderShapes.append(e.pyglet.shapes.Rectangle(org[0], org[1], sz[0] - 2, sz[1] - 2, (130, 130, 130, 255), batch=batch))
	renderShapes.append(e.pyglet.shapes.Rectangle(org[0] + 2, org[1] + 2, sz[0] - 4, sz[1] - 4, (90, 90, 90, 255), batch=batch))
	renderShapes.append(e.pyglet.text.Label(str(entityviewer_info.get(param, "")), "Consolas", 11, x=org[0] + 3, y=org[1] + (sz[1] / 2) + 1, anchor_x='left', anchor_y='center', batch=batch))
	#document = e.pyglet.text.decode_text(str(entityviewer_info.get(param, "")))
	#document.
	#renderShapes.append(e.pyglet.text.layout.TextLayout(document, sz[0], sz[1], batch=batch))
	buttonLocations.append(buttonEntParameter(org[0], org[1], sz[0], sz[1], param))

class entityproperty():
	def __init__(self, name="NULL", ftype=str):
		self.name = name
		self.ftype = ftype

def entityviewer_populate():
	global cursor
	global cursorindex
	global proplist
	ent = e.getuiElementSelected()

	proplist.clear()
	proplist.append(entityproperty("origin", tuple))
	proplist.append(entityproperty("anchor", tuple))
	proplist.append(entityproperty("justify", tuple))
	proplist.append(entityproperty("size", tuple))
	if (ent.__class__ == uieditor.uipicture):
		proplist.append(entityproperty("image", str))

	entityviewer_generateinfo()

	cursor = Vector.Add(cursor, (72, -32))
	for prop in proplist:
		renderShapes.append(e.pyglet.text.Label(prop.name.upper(), "Consolas", 13, x=cursor[0], y=cursor[1], bold=True, anchor_x='right', anchor_y='center', batch=batch))
		if (prop.ftype == tuple):
			entityviewer_box((cursor[0] + 16, cursor[1] - 12), (64, 24), prop.name.lower() + "_x")
			entityviewer_box((cursor[0] + 96, cursor[1] - 12), (64, 24), prop.name.lower() + "_y")
		elif (prop.ftype == str):
			entityviewer_box((cursor[0] + 16, cursor[1] - 12), (512, 24), prop.name.lower())
			#TextWidget(prop.name.lower(), cursor[0] + 16, cursor[1] - 12, 512, batch=batch)
		cursor = Vector.Add(cursor, (0, -32))

def render():
	global cursor
	global cursorindex
	global entityviewer_size

	# draw tool elements
	buttonLocations.clear() # clear button list, since we're about to regenerate them

	glEnable(GL_SCISSOR_TEST)

	entityviewer_size = 0
	if (e.getuiElementSelected()):
		entityviewer_size = min(200, e.toolbar_windowSize[1] * 0.5)

	# draw bottom box
	if (entityviewer_size > 0):
		cursor = (0, entityviewer_size)
		cursorindex = 0

		glScissor(0, 0, e.toolbar_windowSize[0], entityviewer_size)
		renderShapes.append(e.pyglet.shapes.Rectangle(0, 0, e.toolbar_windowSize[0], entityviewer_size, (60, 60, 60, 255), batch=batch))
		entityviewer_populate()
		# top bar
		renderShapes.append(e.pyglet.shapes.Rectangle(0, entityviewer_size - 4, e.toolbar_windowSize[0], 4, (80, 80, 80, 255), batch=batch))
		renderShapes.append(e.pyglet.shapes.Rectangle(0, entityviewer_size - 2, e.toolbar_windowSize[0], 2, (95, 95, 95, 255), batch=batch))
		# pass to renderer
		batch.draw()
		renderShapes.clear()

	#draw elements
	cursor = e.toolbar_window.get_size()
	cursor = (0, cursor[1])
	cursorindex = 0

	glScissor(0, entityviewer_size, e.toolbar_windowSize[0], e.toolbar_windowSize[1] - entityviewer_size)
	recurseList(e.entMaster)
	batch.draw()
	renderShapes.clear()
	
@e.toolbar_window.event
def on_mouse_press(x, y, button, modifiers):
	if (y > entityviewer_size):
		if (button == e.pyglet.window.mouse.LEFT):
			for btn in buttonLocations:
				if (btn.__class__ != buttonEntity):
					continue
				if (not e.check_aabb((x, y), (btn.x, btn.y), Vector.Add((btn.x, btn.y), (btn.width, btn.height)))):
					continue
				if (btn.ent.entList and x < btn.x + 24):
					btn.ent.flags ^= UIFLAG.DROPDOWN
				else:
					e.uiElementSelected = None
					if (e.toolbox_uiElementSelected == btn.ent):
						e.toolbox_uiElementSelected = None
					else:
						e.toolbox_uiElementSelected = btn.ent
				return
			e.toolbox_uiElementSelected = None
		elif (button == e.pyglet.window.mouse.RIGHT):
			for btn in buttonLocations:
				if (btn.__class__ != buttonEntity):
					continue
				if (not e.check_aabb((x, y), (btn.x, btn.y), Vector.Add((btn.x, btn.y), (btn.width, btn.height)))):
					continue
				btn.ent.flags ^= UIFLAG.HIDE
				

@e.toolbar_window.event
def on_mouse_motion(x, y, dx, dy):
	e.toolbox_uiElementHover = None
	if (y > entityviewer_size):
		for btn in buttonLocations:
			if (btn.__class__ != buttonEntity):
				continue
			if (not e.check_aabb((x, y), (btn.x, btn.y), Vector.Add((btn.x, btn.y), (btn.width, btn.height)))):
				continue
			e.toolbox_uiElementHover = btn.ent

@e.toolbar_window.event
def on_mouse_leave(x, y):
	e.toolbox_uiElementHover = None
		

@e.toolbar_window.event
def on_resize(width, height):
	e.toolbar_refresh = True

@e.toolbar_window.event
def on_draw():
	e.toolbar_window.switch_to()
	e.toolbar_windowSize = e.toolbar_window.get_size()

	global tb_refresh_frames
	if (e.toolbar_refresh == True or 1):
		e.toolbar_refresh = False
		tb_refresh_frames = 2

	# things changed... do a flip!
	if (tb_refresh_frames > 0):
		tb_refresh_frames -= 1 # reduce frames
		e.toolbar_window.clear()
		e.toolbar_refresh = False
		render()
		e.toolbar_window.flip()
	e.pyglet.gl.glFinish()
		



