require 'scripts/gui/gui.lua'

--------------------------------------------------------------------------------
-- GUIList Object script
--! 
--! States
--! * idle
--! * disabled
--!
--! Attributes
--! * listener : script component that listens to the element events.
--! * idleVisual : visual for idle state.
--! * focusedVisual : visual for focused state.
--! * disabledVisual : visual for disabled state.
--! * direction : either "horizontal" or "vertical" or "both". Default : "horizontal"
--! * elements : world node that will contain all the list elements. If not provided, it will be automatically created
--! * scroll : reference to the GUIScroll element
--! * scrollBarH : reference to the GUISlider element used for the horizontal scrollbar (optional) 
--! * scrollBarV : reference to the GUISlider element used for the vertical scrollbar (optional)
--! 
--! Events
--! * onElementFocus(element)
--! * onElementUnfocus(element)
--!
--------------------------------------------------------------------------------

GUIList = class(GUIElement)

--------------------------------------------------------------------------------
-- start
--! @brief Callback when the object is added to the world
--------------------------------------------------------------------------------
function GUIList:start()

	GUI:debugPrint("[" .. tostring(self) .. "]\tGUIList:start()", "runtime")
	
	if not self.scroll then
		GUI:error("GUIList must have a reference to a GUIScroll element")
		return
	end
	
	self.scroll = ScriptComponent_getScriptTable(self.scroll)
	self:enforceListenerToSelf(self.scroll, "GUIList", "GUIScroll")

	if self.scrollBarH then
		self.scrollBarH = ScriptComponent_getScriptTable(self.scrollBarH)
		self.scrollBarH.direction = "horizontal"
		self:enforceListenerToSelf(self.scrollBarH, "GUIList", "GUISlider")
		self.scrollBarH:setValue(1 - self.scroll.scrollXValue)
	end
	if self.scrollBarV then
		self.scrollBarV = ScriptComponent_getScriptTable(self.scrollBarV)
		self.scrollBarV.direction = "vertical"
		self:enforceListenerToSelf(self.scrollBarV, "GUIList", "GUISlider")
		self.scrollBarV:setValue(1 - self.scroll.scrollYValue)
	end
	
	GUIElement.start(self)

end

function GUIList:onSliderValueChange(slider, value)
	if slider == self.scrollBarH then
		self.scroll:scrollPercentX(1 - value)
	elseif slider == self.scrollBarV then
		self.scroll:scrollPercentY(1 - value)
	end
end

function GUIList:onScroll(scroll, valueX, valueY)
	if scroll == self.scroll then
		if self.scrollBarH then
			self.scrollBarH:setValue(1 - valueX)
		end
		if self.scrollBarV then
			self.scrollBarV:setValue(1 - valueY)
		end
	end
end

function GUIList:setScrollValues(valueX, valueY)
	if self.scrollBarH then
		self.scrollBarH:setValue(valueX)
		self.scroll:scrollPercentX(1 - valueX)
	end
	if self.scrollBarV then
		self.scrollBarV:setValue(valueY)
		self.scroll:scrollPercentY(1 - valueY)
	end
end
