------------------------------------------------------
--fonctions à mettre ds un fichier à part

.namespace TestFunctions
--rajoute des mots pour la complétion

g_Keywords = {} -- name : nom à afficher ou à mettre en argument, aide : pour les fonctions, 
				-- onwii si nil ou false on n'affiche pas sur la wii, 
				-- shortcut permet de taper l'argument sans taper la function.
FunctionParsing = {}


function InitKeyWords()
   
	for u,v in pairs(FunctionParsing) do
		table.insert(g_Keywords,{name=u,fct="function",aide =v.aide , onwii = v.onwii})
	end
	
	
	local function AddObjects(ut)
		name = string.gsub(ut.Name,"Inventory","")
		table.insert(g_Keywords,{name=name,fct="getobject"})
		--on l'insére aussi en raccourci
		table.insert(g_Keywords,{name=name,fct="function", shortcut = "getobject"}) 
	end
	ApplyToClass("InventoryObject",AddObjects)

	local function AddSite(ut)
		table.insert(g_Keywords,{ name=ut.Name , fct="jumpto" })
		--on l'insére aussi en raccourci
		table.insert(g_Keywords,{ name= ut.Name , fct="function", shortcut = "jumpto" }) 
	end
	ApplyToClass("SearchSite",AddSite)
	ApplyToClass("Closeup",AddSite)
	
	for name,tab in pairs(CUTSCENEDESC) do
		table.insert(g_Keywords,{name=name ,fct="testcutscene"})
	end
	
	--pour la langue, on fait à la mano tant pis
	table.insert(g_Keywords,{name= "fre" ,fct="switchlang"})
	table.insert(g_Keywords,{name= "eng" ,fct="switchlang"})
	table.insert(g_Keywords,{name= "ita" ,fct="switchlang"})
	table.insert(g_Keywords,{name= "ger" ,fct="switchlang"})
	table.insert(g_Keywords,{name= "spa" ,fct="switchlang"})
	
	
	local enum
	 	
	enum = Load("GameVariables","DataArray").GetEnum()
	for u,tab in pairs(enum) do
		for index,name in pairs(tab) do
			table.insert(g_Keywords,{name=name,fct=u})
		end
	end
	
	for u,name in pairs({"GameVariables","UserData"}) do -- bourrin !
		local puzzle= Load(name,"DataArray").GetDataArray()
		for u,v in pairs(puzzle)  do
			table.insert(g_Keywords,{name=u,fct="setvariable"})
		end
	end	
	
	local function AddAnimations(ut)
		table.insert(g_Keywords,{ name=ut.Name , fct="playanimation" })	
	end
	ApplyToClass("Animation",AddAnimations)
	
	UpdateDebugPuzzle()
	
	table.sort(g_Keywords,Compare)
	
end

--compara deux element d'un tableau afficher dans l'rdre alphabétique
function Compare(el1,el2)
	return (tostring(el1.name) < tostring(el2.name)) 
end


function ChangePuzzleValue()
	local newvalue = TestCenter.g_argtable[2]
	if newvalue == "true" then
		newvalue = true
	elseif newvalue == "false" then
		newvalue = false
	end
	local number = tonumber(TestCenter.g_argtable[2])

	local data = GetCurrentLevelData()
	
	if number ==nil then
		data.Set(TestCenter.g_argtable[1],newvalue)	
	else
		data.Set(TestCenter.g_argtable[1],number)	
	end
end

function ChangeVariableValue()
	local newvalue = TestCenter.g_argtable[2]
	if newvalue == "true" then
		newvalue = true
	elseif newvalue == "false" then
		newvalue = false
	end
	local number = tonumber(TestCenter.g_argtable[2])

	
	if GameVariables.IsRegistered(TestCenter.g_argtable[1]) then
		if number ==nil then
			SetVariables(TestCenter.g_argtable[1],newvalue)	
		else
			SetVariables(TestCenter.g_argtable[1],number)	
		end
	else
		if number ==nil then
			SetUserData(TestCenter.g_argtable[1],newvalue)	
		else
			SetUserData(TestCenter.g_argtable[1],number)	
		end
	end
end

--enable ou disable une unit
function Activate()
	local ut=OPUnitFactory.GetUnit(TestCenter.g_argtable[1])
	ut.Enabled = not ut.Enabled
	ut.Flags_Visible = ut.Enabled
end

--met à jour les keywords "activate"
--pas utilisé actuellement
function UpdateDebugPuzzle()
	OPLog.Log("updatedebugpuzzle")

	--on clean d'abord
	for u,tab in pairs(g_Keywords) do
		if (tab.fct == "activate" or tab.fct == "setpuzzle") then
			g_Keywords[u] = nil
		end
	end

	
	for index,val in pairs(DataArrays[GetCurrentLevelData().Name]) do
		table.insert(g_Keywords,{name=index,fct="setpuzzle"})
	end

	for index,tab in pairs(EnumDataArrays[GetCurrentLevelData().Name]) do
		for ind,name in pairs(tab) do
			--OPLog.Log("on rajoute "..index.." "..name)
			table.insert(g_Keywords,{name=name,fct=index})
		end
	end

end

--arg1 destination
function JumpTo()
	OPLog.Log("jumpto : "..TestCenter.g_argtable[1])
    --on essayer de trouver un warp avec arg[1]
    local ut=OPUnitFactory.GetUnit(TestCenter.g_argtable[1])
    
    if ut ~= nil then
		NavigationManager.SwitchTo(nil,TestCenter.g_argtable[1])
    end
end

--pour rajouter ou virer un objet
function GetObject()
	--local ut=Load("Inventory"..TestCenter.g_argtable[1],"InventoryObject")
	InventoryManager.AddInInventory("Inventory"..TestCenter.g_argtable[1])
	--ut.Present = not ut.Present
end

function ShowPuzzle()
	TestCenter.g_showing = true
	--à remplacer
	TestCenter.g_currentdataarray= "SampleLevel"
end


function HideData()
	TestCenter.g_showing = false
	TestCenter.g_dataarraytext.Text=""
end

function ShowVariables()
	TestCenter.g_showing = true
	TestCenter.g_currentdataarray="GameVariables"
end

function ShowUserData()
	TestCenter.g_showing = true
	TestCenter.g_currentdataarray="UserData"
end

function ShowProfilData()
	TestCenter.g_showing = true
	TestCenter.g_currentdataarray="ProfilConfig"
end

function ShowStat()
	TestCenter.g_showing = true
	TestCenter.g_currentdataarray = "Statistics"
end

function ShowSoundCache()
	TestCenter.SetUpdateFct(ShowSoundCacheUpdate)
	for i = 1,15 do
		Disable("ConsoleText"..i,"Text")
	end
end

function ShowSoundCacheUpdate()
	local soundCacheTab = SoundPlayer.GetSoundCache()
	local iter = 1
	
	for i, sound in pairs(soundCacheTab) do
		Enable("ConsoleText"..iter,"Text").Text = "Type : "..sound.Type.." - Volume : "..sound.Volume
		iter = iter + 1
	end
	
	Enable("ConsoleText"..iter,"Text").Text = "\r================\rNb Sound in SoundCache : "..iter - 1
	
	for i = iter + 1, 15 do
		if OPUnitFactory.GetUnit("ConsoleText"..i,"Text").Enabled == true then
			Disable("ConsoleText"..i,"Text")
		end
	end
end

function GetAllObject()
	local function AddObject(ut)
		ut.Equipped = true
	end
	
	ApplyToClass("InventoryObject",AddObject)
	Search_ButtonInventory.UpdateVignettes()

end

function ShowProfiling()
	Load("Profiler","Unit").DisplayProfiling()
end

function SaveGame()
	SaveManager.saveGame("Profil1")
end

function LoadGame()
	SaveManager.loadProfile()
	SaveManager.loadGame("Profil1",true)
end


function TestCutscene()
	--Load("CutsceneAllTest","Cutscene").Enabled = not Load("CutsceneAllTest","Cutscene").Enabled 
	Enable("CutscenePlayer","Unit").StartCutscene(TestCenter.g_argtable[1])
end


function PreloadLevel()
	local ut=Enable("LoadingScreen","Sprite")
	ut.Preload(TestCenter.g_argtable[1])
end

function StopCurrentMusic()
	function StopMusic(ut)
		if ut.Type =="Music" then
			ut.Stop()
			ut.OnEndSound()
		end
	end
	ApplyToClass("SimpleSound",StopMusic)
end

function GetObjectByScreen()
	local screen = GetCurrentManager()
	g_tabObjects = {}
	OPLog.Log("scanning "..screen.Name)
	AddChildrenObjectsToTab( screen )
	OPLog.Log(table.getn(g_tabObjects).." objects found")
	local nextNbObject = InventoryManager.NbObject
	for i, object in pairs(g_tabObjects) do
		if object.InventoryObject~= nil then
			nextNbObject = nextNbObject + 1
		end
	end
	OPLog.Log("next nb inventory objects : "..nextNbObject)
	if nextNbObject > 7 then
		AssertPopup(false,"Action annulée, vous devez tout d'abord\r retirer au moins\r "..(nextNbObject-7).." objets de l'inventaire")
	else
		for i, object in pairs(g_tabObjects) do
			InventoryManager.AddObjectToInventory(object)
		end
		OPLog.Log(" -------- adding completed ----------- ")
	end
	g_tabObjects = nil
end

function AddChildrenObjectsToTab( unit )
	local iter = 0
	local child = unit.Children[0]
	local listOfChildren = ""
	while child~= nil do
		listOfChildren = listOfChildren.." | "..child.Name
		if child.ClassName == "Object" 
			and NavigationManager.GetCurrentLevelData().Get(child.Name) < 2
		then
			OPLog.Log("adding "..child.Name.." to inventory")
			table.insert( g_tabObjects, child )
		elseif child.ClassName == "AreaCloseup" and child.Destination ~= nil then
			local closeup = OPUnitFactory.GetUnit(child.Destination)
			OPLog.Log("scanning closeup "..closeup.Name)
			AddChildrenObjectsToTab( closeup )
		else
			AddChildrenObjectsToTab( child )
		end
		
		iter = iter + 1
		child = unit.Children[iter]
	end
end

--exemple création d'unit
function CreateGUIText()
    local path,ok
	oplpath="opl/2DGames/Alimentation.opl"
    unit=OPUnitFactory.CreatePermanentUnit('GUIUnicodeText',oplpath)
    unit.Font = "../../Sprite/fonts/ARIAL.ttf"

    unit.UpdateInitialState()
    
end

function TestCredits()
	ut=Enable("CreditsManager","Unit")
	ut.StartCredits(true)
end

function TakeScreenShot()
	surf=OPUnitFactory.CreateUnit('Sprite')
	surf.TakeSnapshot()
	surf.Layer= LayerGUI1
end

function testsequence()
	--PlaySoundEffect("CS_04_A03_01")
	Enable("SequencePlayer","Unit").PlaySequence("CS_09_A01_01")
end

function SetAlphaThreshold()
	OPLog.Log("Application de l'AlphaTestThreshold aux Backgrounds / Archaeo Wii")
	local unit,b=OPUnitFactory.GetFirstUnit('Background',1)
    while (unit~= nil) do
        if unit.Parent ~= nil and unit.Parent~= nil and unit.Parent.ClassName == 'Excavation_Site'
				and unit.Layer ~= nil and unit.Layer~= nil and unit.Layer.Name ~= 'LayerBackground' then
			unit.AlphaTest = true
			unit.AlphaTestThreshold = 200
			unit.UpdateInitialState()
		elseif unit.Parent ~= nil and unit.Parent~= nil and unit.Parent.ClassName == 'Excavation_Site'
				and unit.Layer ~= nil and unit.Layer~= nil and unit.Layer.Name == 'LayerBackground' then
			unit.AlphaTestThreshold = false
			unit.AlphaTestThreshold = 0
			unit.UpdateInitialState()
		elseif unit.Layer == nil or unit.Layer== nil then
			OPLog.Log(unit.Name.." n'a pas de layer")
		end
		
		if string.find(unit.Name, "d03") ~= nil then
			unit.NoIntercept = true
			OPLog.Log(unit.Name.." : NoIntercept updated")
			unit.UpdateInitialState()
		end
		
        unit=OPUnitFactory.GetNextUnit(b)
    end
	
	OPLog.Log("Application de l'AlphaTestThreshold aux SpriteGameplays")
	local unit,b=OPUnitFactory.GetFirstUnit('SpriteGameplay',1)
	while unit~= nil do
		if unit.Parent ~= nil and unit.Parent~= nil and unit.Parent.ClassName == 'Background' then
			unit.AlphaTest = true
			unit.AlphaTestThreshold = 200
			unit.UpdateInitialState()
		else
			OPLog.Log(unit.Name.." n'a pas été mis-à-jour")
		end
        unit=OPUnitFactory.GetNextUnit(b)
	end
	
	OPLog.Log("Fin de mise à jour")
end


function ShowEnabled()
	OPLog.Log("---------------Enabled ---------------")
	ApplyToClass("SpriteGameplay",DisplayName)
	ApplyToClass("Animation",DisplayName)
	OPLog.Log("---------------Fin Enabled ---------------")
end

function DisplayName(ut)
	if ut.ParentEnabled then
		OPLog.Log(ut.Name.." "..ut.ClassName)
	end
end


function OnSwitchEnd(name)
	OPLog.Log("onswitch end "..name)
	
end

function ShowUnitsAt()
	local res = TestCenter.SetUpdateFct(ShowUnitAtUpdate)

	if res then
		Enable("ConsoleText1","Text").LineSpacing = -15
	else
		Disable("ConsoleText1","Text")
	end

end

function ShowUnitAtUpdate()
	local x = Cursor.Position_X + Cursor.Hotspot_X
	local y = Cursor.Position_Y + Cursor.Hotspot_Y
	local tab = OPScene.UnitsAt(x,y)
	local res
	
	if Cursor.Enabled then
		res = GlobalFunctions.DisplayUnitsTab(tab).."\r================\r"..GlobalFunctions.DisplayUnitsTab(Cursor.TabUnitsAt)
	else
		res = GlobalFunctions.DisplayUnitsTab(tab)
	end
	
	--OPLog.Log("showunits "..res)
	Enable("ConsoleText1","Text").Text = res
	
end

function TestGlobalVolume()
	OPLog.Log("setglobalvolume "..TestCenter.g_argtable[1]/100)
	OPSoundManager.SetGlobalVolume(TestCenter.g_argtable[1]/100)
end

function ShowSafeFrame()
	SpriteSafeFrame.Enabled = not SpriteSafeFrame.Enabled 
end

function TestAnimation()
	Level02Data.Set("CS_02_A01_01", true)
	Level02Data.Set("L02_S01_DynamiteSpot", "L02_S01_Hole1")
	NavigationManager.SwitchTo(nil,"L02_S01",self)
end

function SwitchLang()
	GlobalFunctions.UpdateLang(TestCenter.g_argtable[1])
end

function VsprTest()
	L09_S06_SR_Test.Enabled = true
	L09_S06_SR_Test.Play()
end

function SwitchTo()
	SwitchToCommon()
	NavigationManager.SwitchTo(nil,TestCenter.g_argtable[1],self)
end

function SwitchToWii()
	SwitchToCommon()
	NavigationManager.SwitchTo(nil,TestCenter.g_argtable[1].."_S01",self)
end

function SwitchToWiiExpand()
	SwitchToCommon()
	NavigationManager.SwitchTo(nil,TestCenter.g_argtable[1].."_"..TestCenter.g_argtable[2],self)
end

function SwitchToCommon()
	ScoringManager.Enabled = true
	SaveManager.loadProfile() --pour pas écraser les profils en cours
	SetUserData("a_"..string.sub(TestCenter.g_argtable[1],1,3),true) --on rend le niveau accessible depuis la carte
		
	if string.find(TestCenter.g_argtable[1],"L05") then
		SetUserData("GotPowder",true)
	end
	
	if string.find(TestCenter.g_argtable[1],"V02") then
		SetUserData("a_R02",true)
	end
	
	if string.find(TestCenter.g_argtable[1],"V03") then
		SetUserData("a_R03",true)
	end
	
	local level = tonumber(string.sub(TestCenter.g_argtable[1],2,3))
	if level > 7 then
		SetUserData("a_R03",true)
	elseif level > 4 then
		SetUserData("a_R02",true)
	end
	
	SetUserData("a_"..string.sub(TestCenter.g_argtable[1],1,3),true)
	
	
	-- on charge le pak "permanent" ici, comme ça on un visuel assez vite et pas de sentiment de temps d'attente
	if IsEqualVariables("GameStarted",false) and  OPCore.GetPlatform() == "Wii"  then
		OPLog.Log("chargement pak permanent")
		OPPak.LoadPak("Permanent")
	end
	
	SetVariables("GameStarted",true)
		
end

function PlayVideo()
	GlobalFunctions.PlayVideo(TestCenter.g_argtable[1])
end

function AddObject(ut)
	InventoryManager.Enabled = true
	InventoryManager.AddInInventory(ut.Name)
end

function PopupTest()
	PopupManager.OpenPopup("TXT_SYSTEM_TRC_SAVE_CORRUPT",self)
end

function OnPopupLeave()
	OPLog.Log("popupleave")
end

function PrintBadSprite()
	curstring = ""
	
	ApplyToClass("SpriteGameplay",PrintOneBadSprite)
	ApplyToClass("Sprite",PrintOneBadSprite)
end


function PrintOneBadSprite(ut)
	if string.find(ut.Image,"_wall") or string.find(ut.Image,"_floor") then
		OPLog.Log("sprite "..ut.Name.." du parent "..ut.Parent.Name.." pas bon")
	end
end


function TestViewPort()
	OPGraphic.SetDefaultViewport(0,60,640,420)
	if OPCore.GetPlatform() == "Wii" then
		OPGraphic.SetScale2D(1,0.75)
	end
	--
end

function CheckNameLoc()
	ApplyToClass("Object",CheckOneNameLoc)
	ApplyToClass("InventoryObject",CheckOneNameLoc)
end

function CheckOneNameLoc(object)
	local res
	if object.Type == "Object" then
		if object.InventoryObject== nil then
			OPLog.Log("Erreur, mauvais type intégré sur cet objet "..object.Name)
		else
			res = InventoryManager.DiscoverObject( object.InventoryObject.NameLoc, "Object", object )
		end

	else
		res= InventoryManager.DiscoverObject( object.NameLoc, object.Type, object )
	end
	
	if not res then
		OPLog.Log("prob loc sur "..object.Name)
	end
end

function CheckOneNameLocInventory(object)
	local res
	res = DiscoverObject( object.NameLoc, "Object", object )
	
	if not res then
		OPLog.Log("prob loc sur "..object.Name)
	end
end

function SetLevelFinished()
	SetUserData(TestCenter.g_argtable[1].."_Finished",true)
end

function Cheat_FinishCurrentSearch()
	ObjectManager.Cheat_FinishCurrentSearch()
end

function FinishCurrentCloseup()
	OPUnitFactory.GetUnit(GetCurrentManager().Name).FinishCloseUp(TestCenter.g_argtable[1])
end

function PlayAnimation()
	OPUnitFactory.GetUnit(TestCenter.g_argtable[1]).Play()
end

function DisableParticles2D()
	local function ParticulesOff(ut)
		ut.Enabled = false
	end
	ApplyToClass("Particle2DEmitter",ParticulesOff)
end

function UpdateImagePath()
	local ut = unit(TestCenter.g_argtable[1])
	ut.Image = string.gsub(ut.Image,"media\\graph","media\\common\\graph")
	ut.UpdateInitialState()

end

function SetReso()
	OPLog.Log("setreso "..TestCenter.g_argtable[1].." "..TestCenter.g_argtable[2])
	GlobalFunctions.SetGraphicMode(tonumber(TestCenter.g_argtable[1]),tonumber(TestCenter.g_argtable[2]))
end

function TestClass()
	s01_tapisserie_hotspot.Toto()
end

function TestSelfName()
	s01_tapisserie_hotspot.Titi()
end

function TestTimer()
	self.g_Animtimer = GlobalFunctions.CreateTimer(self.Name, 15,true,true, false, self)
	self.g_Animtimer.Enabled=true
	self.g_Animtimer.Start()
end

function CreateAllBackgrounds()
	local oplpath,layer
	local shortname
	
	local chapter = TestCenter.g_argtable[1]
	
	for i=1,24 do
		oplpath="opl/World"
		
		if i<10 then
			shortname = "s0"..i
		else
			shortname = "s"..i
		end
		
		oplpath=oplpath.."/"..shortname..".opl"
		
		local searchsite = OPUnitFactory.GetUnit(shortname.."_SearchSite")
		
		if searchsite == nil then
			searchsite = OPUnitFactory.CreatePermanentUnit('SearchSite',oplpath)
			searchsite.Name = shortname.."_SearchSite"
			searchsite.EditorFolder = string.upper(shortname).."\\"
			searchsite.UpdateInitialState()
			searchsite.Enabled = false
		end
		
		--on crée les background
		for k,backname in pairs   ({"foreground","background","middleground"}) do
			local backunit = OPUnitFactory.GetUnit(shortname.."_"..backname)
			if backunit == nil then
				backunit=OPUnitFactory.CreatePermanentUnit('Background',oplpath)
				backunit.Name = shortname.."_"..backname	
				backunit.EditorFolder = searchsite.EditorFolder
				backunit.Parent = searchsite				
				OPLog.Log(" création OK")
			else
				OPLog.Log("l'unit "..backunit.Name.." existe déjà")
			end
			

			OPLog.Log("image ".."media/graph/world/"..shortname.."/c0"..chapter.."_"..shortname.."_"..backname..".png")
			backunit.Image = "media/graph/world/"..shortname.."/c0"..chapter.."_"..shortname.."_"..backname..".png"
			if backname == "foreground" then
				layer = unit("LayerForeground")
			elseif backname == "background" then
				layer = unit("LayerBackground")
			elseif backname == "middleground" then
				layer = unit("LayerMiddleground")
			end
			backunit.Layer = layer
			
			backunit.Parent.UpdateInitialState()
			backunit.UpdateInitialState()
		end
	end
end

function CreateCloseup()
local oplpath,layer
	local shortname
	
	local chapter = TestCenter.g_argtable[1]
	local i = tonumber(TestCenter.g_argtable[2])

	oplpath="opl/World"
	
	if i<10 then
		shortname = "s0"..i
	else
		shortname = "s"..i
	end
	
	oplpath=oplpath.."/"..shortname..".opl"
	
	local searchsite = OPUnitFactory.GetUnit(shortname.."_c01_Closeup")
	
	if searchsite == nil then
		searchsite = OPUnitFactory.CreatePermanentUnit('Closeup',oplpath)
		searchsite.Name = shortname.."_c01_Closeup"
		searchsite.EditorFolder = string.upper(shortname).."\\"
		searchsite.UpdateInitialState()
		searchsite.Enabled = false
	else
		return
	end
	
	--on crée le background
	local backunit = OPUnitFactory.GetUnit(shortname.."_c01_background")
	if backunit == nil then
		backunit=OPUnitFactory.CreatePermanentUnit('Background',oplpath)
		backunit.Name = shortname.."_c01_background"
		backunit.EditorFolder = searchsite.EditorFolder
		backunit.Parent = searchsite				
		OPLog.Log(" création OK")
	else
		OPLog.Log("l'unit "..backunit.Name.." existe déjà")
	end
	
	OPLog.Log("image ".."media/graph/world/"..shortname.."/c0"..chapter.."_"..shortname.."_c01_background.png")
	backunit.Image = "media/graph/world/"..shortname.."/"..shortname.."_c01/c0"..chapter.."_"..shortname.."_c01_background.png"
	backunit.Parent.UpdateInitialState()
	backunit.UpdateInitialState()
end

function TestMetaTables()
	local mytab = CreateNewArray()
	OPLog.Log(tostring(mytab["test"]).." "..tostring(mytab["t"]))
	mytab["t"] = 5
	mytab.test = "tutu"
	OPLog.Log(tostring(mytab["test"]).." "..tostring(mytab["t"]))
end

-- function TestScrollTuto()
	-- TutorialManager.StartGlobalTuto()
-- end

function TestProbScale()
	SampleLevel.Set("CloseupMecaState","started")
	NavigationManager.SwitchTo(nil,"s01_c01_Closeup")
end

function TestVideo()

	VideoPlayer.PlayVideo("CS0"..TestCenter.g_argtable[1],"s03_SearchSite")
end

function TestRagDoll()
	Menu_titre.Start = false
	RagDoll.Enabled = true
	RagDoll.CreateBox( 200,400, 200, 200 )
	RagDoll.CreateBox( 650,250, 200, 200 )
	RagDoll.CreateBox( 350,50, 200, 200 )
end

function GenerateObjectStat()
	--OPLog.Log("filepath profile "..filepath)
	AssertPopup(type(CURRENTCHAPTER) =="string" , "currentchapter non défini !!" )
	
	local f ,str= OPFileManager.Open("c:/dev/Hidden/Document/"..CURRENTCHAPTER.."_object.txt",'w')

	if (f == nil) then
		OPLog.Log("prob à l'ouverture du fichier tmp.lua "..OPFileManager.GetLastError())
		return false
	end	

	f:Write('stats objets du chapitre '..CURRENTCHAPTER.."\n")
	local screencompteur = {}
	for u,tab in pairs(ObjectData) do
		if screencompteur[tab.screen] == nil then
			screencompteur[tab.screen] = 1
		else
			screencompteur[tab.screen] = screencompteur[tab.screen] + 1
		end		
	end
	--calcul moyenne
	local moy = 0
	local compteur = 0
	local tabtosort = {}
	for u,nb in pairs(screencompteur) do
		if not string.find(u,"cup") then
			moy = moy + nb
			compteur = compteur +1
		end
		table.insert(tabtosort, {name = u, nb = nb})
	end
	
	table.sort(tabtosort , SortScreen)
	f:Write("nb total objet (hors closeup)"..moy.."\n")
	moy = GlobalFunctions.Display(moy /compteur)
	f:Write("moyenne d'objets par écran (hors closeup)"..moy.."\n\n")
	for u,tab in pairs(tabtosort) do
		f:Write(" écran : "..tab.name.." : "..tab.nb.."\n")
	end

	local res = f:Flush()
	f:Close()
	
end

function SortScreen(tab1,tab2)
	return (tab1.name < tab2.name)
end

function DebugSetGamma()
	OPLog.Log("debugsetgamma " ..GlobalFunctions.Display(TestCenter.g_argtable))
	OPGraphic.SetGamma(tonumber(TestCenter.g_argtable[1]) / 100)
end

function TestInclude()
	OPLua.Include("script/DataArray/SampleLevel.lua")
	GetCurrentManager().OnUpdate()
end

function TestHighlightParticles()
	ParticlesHighlightSprite.Enabled = true
	ParticlesHighlightSprite.StartParticlesHighlight(s01_porte_01,Vector:new(1000,100))
end


function SaveProfil()
	SaveManager.saveProfile()
end

function LoadProfil()
	SaveManager.loadProfile()
end

function ResetGame()
	SaveManager.createNewGame()
end

function SetMinConfig()
	GlobalFunctions.g_needtoopenpopupminconfig = true
end

function TestPonctuation()
	VideoText.Enabled = true
	VideoText.Layer =  LayerCursor
	VideoText.Text = "sdfgmlkjsdfguvcblkl dfklljgyl sidudfgsdfgml sdfg ?"
end

function TestAssertPopup()
	AssertPopup(false, " mon test ")
end

--ces fonction sont décentralisé exprés
function OnShortcutOn(key)
	if key ==  KEY_CONTROL then --on rend visible les objets
		ApplyToClass("Object",SetColorTransparent)
		ApplyToClass("CloseupObject",SetColorTransparent)
		return true
	end
end

function OnShortcutOff(key)
	if key ==  KEY_CONTROL then --on rend visible les objets
		ApplyToClass("Object",SetColorOpaque)
		ApplyToClass("CloseupObject",SetColorOpaque)
		return true
	end
end

--j'utilise ces fonctions plutot que visible et pas visible pour pas changer les recherches en cours
function SetColorTransparent(ut)
	ut.Color.a = 0
end

function SetColorOpaque(ut)
	ut.Color.a = 255
end

g_onfullscreen = true
function SwitchFullScreen()
	if g_onfullscreen then
		OPGraphic.SetScreenMode({fullscreen=false}) 
	else
		OPGraphic.SetScreenMode({fullscreen=true}) 
	end
	
	g_onfullscreen = not g_onfullscreen
end

function TestOutline()
	OPLog.Log(GlobalFunctions.Display(s01_tapisserie_hotspot.Outline))
	OPLog.Log(s01_tapisserie_hotspot.Outline[1].x.." "..s01_tapisserie_hotspot.Outline[1].y)
end

FunctionParsing = -- le 4 éme paramétre indique si on met la fonction sur la wii ou pas
{

    jumpto = {fct=JumpTo,nbarg=1,aide="Active le lieu correspondant, Param :  nom dest",onwii = false}, 
   	setpuzzle={fct=ChangePuzzleValue,nbarg=2,aide= "Change val ds puzzle : Param :  nom val à changer, nouv val",onwii = false},
	setvariable={fct=ChangeVariableValue,nbarg=2,aide= "Change la val : Param :  nom val/nouv val",onwii = false},
	getobject={fct = GetObject,nbarg=1,aide = "Rajoute un objet dans l'inventaire : Param nom de l'objet",onwii = false},
	getallobject={fct = GetAllObject,nbarg=0 ,aide = "rajoute tous les objets dans l'inventaire, 0 param",onwii = false},
	showpuzzle={fct = ShowPuzzle,nbarg=0,aide ="affiche l'état du tableau puzzle",onwii = true},
	showvariables = {fct=ShowVariables,nbarg=0,aide = "affiche gamevariables",onwii = true},
	showprofildata = {fct = ShowProfilData,nbarg = 0 ,aide = "affiche profiledata",onwii=true},
	showuserdata = {fct=ShowUserData,nbarg=0,aide = "affiche l'état de userdata",onwii = true},
	hidedata={fct = HideData,nbarg=0,aide ="cache le txt affiché de la fct showpuzzle",onwii = true},
	activate={fct=Activate,nbarg=1,aide = "active une unit précise, param : nom de l'unit",onwii = false},	
	savegame={fct = SaveGame, nbarg=0 , aide ='fait un sauvegarde "checkpoint" ',onwii = true},
	loadgame={fct=LoadGame,nbarg=0 , aide = "recharge la sauvegarde checkpoint",onwii = true},
	saveprofil={fct = SaveProfil, nbarg=0 , aide ='fait un sauvegarde "checkpoint" ',onwii = true},
	loadprofil ={fct=LoadProfil,nbarg=0 , aide = "recharge la sauvegarde checkpoint",onwii = true},
	resetgame = {fct = ResetGame,nbarg = 0 ,aide = "reset des états du jeu "},
	--testcutscene={fct = TestCutscene,nbarg=1,"test une cutscene donné, arg : nom cutscene",onwii = true},
	--blendsound ={fct = BlendSound , nbarg = 1},
	--stopmusic = {fct = StopMusic , nbarg=0,"arrete la musique en cours"},
	showstat = {fct = ShowStat , nbarg =0 , "montre les stats du jeu",onwii = false},
	--testsequence = {fct =  testsequence,nbarg = 0, "test sons",onwii = true},
	--createmap = {fct =  CreateMap,nbarg = 0, "crées les units MapRoom associées aux fichiers de map existants",onwii = false},
	showenabled = {fct = ShowEnabled,nbarg = 0 , "affiche ttes les units enabled",onwii = false},
	showunitats = {fct= ShowUnitsAt , nbarg = 0,"affiche les elements sous la souris", onwii= true},
	--test3d = {fct = Test3D, nbarg = 0 , "test de pioche 3d" , onwii = true},
	testglobalvolume = {fct = TestGlobalVolume , nbarg = 1 ,"test global volume" , onwii = false},
	--createvillagesbg = {fct = CreateVillagesBg , nbarg = 0 ,"crée les backgrounds des villages" , onwii = false},
	--showsafeframe = {fct = ShowSafeFrame,nbarg = 0 ,"Affiche la safe frame",onwii = true},
	--testanimation = {fct = TestAnimation,nbarg =0,"testanim explosion",onwii=true},
	switchlang= {fct = SwitchLang,nbarg = 1 ,"changement langue (parmie les 5)",onwii=true},
	--vsprtest = {fct = VsprTest,nbarg = 0 ,"",onwii=true},
	--switchto = {fct = SwitchTo ,nbarg = 1,"fait un switch sur l'endroit visité",onwii = false},
	--switchtowii = {fct = SwitchToWii ,nbarg = 1,"fait un switch sur le niveau ",onwii = true},
	--switchtowiiexpand = {fct = SwitchToWiiExpand ,nbarg = 2,"fait un switch sur le niveau et l'écran choisi",onwii = true},

	--playvideo = {fct = PlayVideo,nbarg = 1,"joue la video donné",onwii =true},
	addobject = {fct = AddObject,nbarg = 1,"ajout l'objet donné",onwii =false},
	--popuptest = {fct =PopupTest ,  nbarg = 0 ,"test popup",onwii= true},
	--testviewport = {fct = TestViewPort,nbarg = 0 ,"test le viewport 4/3",onwii = true},
	finishcurrentsearch = {fct = Cheat_FinishCurrentSearch, nbarg=0, "finit la recherche en cours"},
	--updateimagepath = {fct = UpdateImagePath , nbarg = 1 ,"met à jour le path image de l'unit"},
	setreso = {fct = SetReso , nbarg = 2 , "test la résolution donnée" },
	--createsearchsite = {fct = CreateAllBackgrounds,nbarg=1,"crée les background"},
	--createcloseup = {fct = CreateCloseup,nbarg = 2 , "crée un closeup pour un chapitre (arg1)et un écran donné (arg2)"},
	--testmetatables = {fct = TestMetaTables , nbarg = 0 , ""},
	--testtuto = {fct = TestScrollTuto,nbarg = 0 ,"lance le tutorial"},
	testprobscale = {fct = TestProbScale  , nbarg = 0 , " réduit plus rapidemment un prob de scale"},
	testvideo = {fct= TestVideo,nbarg = 1,""},
	testragdoll = {fct= TestRagDoll , nbarg = 0 ,""},
	setgamma = {fct = DebugSetGamma , nbarg = 1 ,"set le gamma du jeu (facteur 100)"},
	
	
	finishcurrentcloseup = {fct = FinishCurrentCloseup , nbarg = 1, "finit le closeup en cours", onwii = true },
	playanimation = { fct = PlayAnimation, nbarg = 1, "joue l'animation passée en paramètre", onwii = true },
	disableparticles2d = { fct = DisableParticles2D, nbarg = 0, "Désacive les particules 2D", onwii = true },
	generateobjectstat = { fct = GenerateObjectStat , nbarg = 0 ,"génére les stats pourun objet donné dans le repertoire racine"},
	testinclude = {fct = TestInclude , nbarg = 0 ,"test oplua include"},
	testhighlighparticles = { fct = TestHighlightParticles , nbarg = 0 ,""},
	minconfig = {fct = SetMinConfig , nbarg = 0 , "on définit la minconfig "},
	
	testponctuation = {fct = TestPonctuation , nbarg =0, "testponctuation pour didier",},
	assertpopup = { fct = TestAssertPopup ,  nbarg = 0 , "assertpopup" , }, 
	switchfullscreen = { fct = SwitchFullScreen , nbarg = 0 , "switchfullscreen"},
	testoutline = {fct = TestOutline , nbarg = 0,""},
	
}


