dofile ( "Scripts/mouse_utils.lua" )

dofile ( "Scripts/button.lua" )
dofile ( "Scripts/slider.lua" )
dofile ( "Scripts/drag_selectable.lua" )
dofile ( "Scripts/input_field.lua" )


gui_elements = {}
focus = nil
hover = nil

function InitGUI ( )

	if mouse then
		InitMouse ( )


		mouse.OnPress = function ( button, x, y )
			if focus and focus:TestPoint ( x, y ) == false then
				-- deselect the old gui element
				focus:LoseFocus ( )
				focus = nil
			end
			local top
			-- find the 'highest' z-order element
			for i, v in pairs ( gui_elements ) do
				if v:TestPoint ( x, y ) == true then
					if top == nil or top.z > v.z then
						top = v
					end
				end
			end
			if top then
				if top ~= focus then
					focus = top
					focus:GainFocus ( )
				end
				focus:MousePress ( button, x, y )
			end
		end

		mouse.OnRelease = function ( button, x, y )
			if focus then
				focus:MouseRelease ( button, x, y )
			end
		end
		mouse.OnBeginDrag = function ( button, x, y )
			if focus then
				focus:BeginDrag ( button, x, y )
			end
		end
		mouse.OnEndDrag = function ( button, x, y )
			if focus then
				focus:EndDrag ( button, x, y )
			end
		end
		mouse.OnDragging = function ( button, x, y )
			if focus then
				focus:Dragging ( button, x, y )
			end
		end
		mouse.OnSingleClick = function ( button, x, y )
			if focus then
				focus:SingleClick ( button, x, y )
			end
		end
		mouse.OnDoubleClick = function ( button, x, y )
			if focus then
				focus:DoubleClick ( button, x, y )
			end
		end
		mouse.OnWheelMove = function ( z )
			if focus then
				focus:WheelMove ( z )
			end
		end
		mouse.OnMove = function ( x, y )
			-- find the 'highest' z-order element
			local top
			for i, v in pairs ( gui_elements ) do
				if v:TestPoint ( x, y ) == true then
					if top == nil or top.z > v.z then
						top = v
					end
				end
			end
			if top ~= hover then
				if hover then
					hover:ExitHover ( x, y )
				end
				if top then
					top:EnterHover ( x, y )
				end
				hover = top
			else
				if hover then
					hover:Hover ( x, y )
				end
			end
		end
	end


	if keyboard then
		keyboard.on_press = function ( key )
			if focus then
				focus:KeyPress ( key )
			end
		end
		keyboard.on_release = function ( key )
			if focus then
				focus:KeyRelease ( key )
			end
		end

	end

end


function AddGUIElement ( et )
	table.insert ( gui_elements, et )
end

function RemoveGUIElement ( et )
	for i, v in pairs ( gui_elements ) do
		if v == et then
			table.remove ( gui_elements, i )
			break
		end
	end
	if focus == et then
		focus = nil
	end
	if hover == et then
		hover = nil
	end
end

function SetFocus ( et )
	focus = et
	if focus then
		focus:GainFocus ( )
	end
end