collectgarbage ("stop")
-- globals

pUIScene = nil
pWidgetArray = {}

function SetUIScene(sObject)
	pUIScene = sObject
	table.insert (pWidgetArray, pUIScene)
end

function GetObjectByName (sObjectName)
	local pObject = nil
	for name, ctor in pairs (GUI) do
		if name == sObjectName then
			pObject = ctor ()
            GUI.swig_unown(pObject)
		end
	end
	if pObject == nil then
		print ("Lua Error: can't get ctor for " .. sObjectName)
	end
	return pObject
end

function GetMethod (pObject, sMethodName)
	local pMethod = nil
	for name, func in pairs (getmetatable (pObject)[".fn"]) do
		if name == (sMethodName) then
			pMethod = func
			break
		end
	end
	return pMethod
end

function CallMethod (pObject, sMethodName, Value)
	local pMethod = GetMethod (pObject, sMethodName)
	if pMethod then
		pMethod (pObject, Value)
	else
		print ("Lua error: can't get method " .. sMethodName .. " for object of type " .. getmetatable (pObject)[".type"])
	end
end

function CallMethodByName (sObjectType, sObjectPath, sMethodName, sArgumentPath)
	local pSource = nil
	if sObjectType == "Widget" then 
		pSource = pUIScene:GetWidgetAtPath (sObjectPath)
	end
	local pDestination = GetWidgetAtPath (sArgumentPath)
	CallMethod (pSource, sMethodName, pDestination)
end

function GetTexture (sFileName)
	pScene = pUIScene:GetScene ()

	if sFileName == nil then
		return nil
	else
		local fileInfo = GetObjectByName ("FileInfo")
		CallMethod (fileInfo, "SetResource", sFileName)
		if pScene then
			local TextureBank = pScene:GetTextureBank()
			return TextureBank:GetTexture (fileInfo)
		else
			print ("Lua error : Cannot get the Scene")
			return nil
		end
	end
end

function GetWidgetAtPath (sPath)
	pWidget = pUIScene:GetWidgetAtPath (sPath)
	return pWidget;
end

function popObject ()
	table.remove (pWidgetArray, #pWidgetArray)
end

function pushObject (pObject)
	table.insert (pWidgetArray, pObject)
end

function GetTableSize()
	return table.getn(pWidgetArray)
end

function lastObject ()
	pValue = pWidgetArray[#pWidgetArray]
	return pValue;
end

function secondLastObject ()
	pValue = pWidgetArray[#pWidgetArray - 1]
	return pValue;
end

function CreateObjectByNameAndPush (sName)
	pObject = GetObjectByName (sName)
	pushObject (pObject)
end

function CreateTextureAndPush (sTextureName)
	pObject = GetTexture (sTextureName)
	pushObject (pObject)
end

function CallMethodWithOneArgumentAndPop (sMethodName)
	CallMethod (secondLastObject (), sMethodName, lastObject ())
	popObject ()
end

function CallMethodWithOneArgument (sMethodName)
	CallMethod (secondLastObject (), sMethodName, lastObject ())
end