
.namespace TestCenter

LINENB = 90
LINEBYCOLLUMN = 33
LINESPACING = 28
COLWIDTH = 500

g_argtable={}
g_CurrentCompletionList = {}
g_waitingforarg = false
g_commandwiicache = {}
   
g_curfctcall=nil

--pour la complétion
g_choosingbetweencompletionlist = false
g_indexincompletionlist = 0
g_active = false
--ici on bind tous les test necessaires
-- pour les datasarray
g_showing = false
g_currentdataarray=""

g_showhelp = false
g_currentkeywordtype ="function" --pour la complétion
g_counterframe = 0
g_timecounter = 0
g_curselection = 0

g_lastloadtime = 0
g_currentcmd = ""
	
g_dataarraytext = nil
g_displaytext = nil

g_firstframe = true
g_curupdatefct = {}
	
function OnEnable()
	
	self.Flags_AcceptAllInputs = true
	
	RegisterListenerGen(EVENT_KEY_DOWN+EVENT_KEY_UP,EVENT_PAD_BUTTON_DOWN+EVENT_PAD_BUTTON_UP)
	
	OPLog.Log("plateforme "..OPCore.GetPlatform() )
	
    OPInput.SetListenerPriority(TestCenter,LISTENER_HIGH_PRIORITY)
    	
end

function OnFirstFrame()
	g_firstframe = false
	
    g_displaytext = Disable("DebugCmdText","Text")
	--g_curupdatefct.fct = nil
	
	Disable("DebugDisplayText","Text")
	
	g_dataarraytext=Load("Text_Sprite","Text")
	g_dataarraytext.LineSpacing = -15
	InfoText.LineSpacing = -19
		
	Text_Sprite.Scale_X = 0.8
	Text_Sprite.Scale_Y = 0.8
    

    TestFunctions.InitKeyWords()
	
	InitInfoText()
		
	UpdateInfo("function")
	
	g_curupdatefct = {}
	g_curupdatefct.fct = nil
	--OPLog.Log("editor folder "..self.EditorFolder)

	InfoText.CharSpacing = -1
end


function SetLastLoadTime(val)
	g_lastloadtime = val
end

function InitInfoText()
	for i=0,LINENB do
		CreateTextLine(i)
	end
end

function UpdateTextColor()
	for i=0,LINENB do
		local text= Load("ConsoleText"..i,"Text")
		if i == g_curselection then
			text.Color.r = 255
			text.Color.g = 255
			text.Color.b = 0
		else
			text.Color.r = 255
			text.Color.g = 255
			text.Color.b = 255		
		end
	end
end

function OnUpdate(dt)
	local s
	
	--à virer par la suite
	--DebugDisplayText.Text = SampleLevel.DisplayAll()
	
	if g_firstframe then	
		OnFirstFrame()
		return
	end

	if g_showing and g_active then
		s = OPUnitFactory.GetUnit(g_currentdataarray,"DataArray").DisplayAll()	
		if g_currentdataarray == "GameVariables" then
			s=s.."---------------------\n"
			s=s..UserData.DisplayAll()
		end
		g_dataarraytext.Text=s
		Enable(g_dataarraytext)
	end
	
	if (GlobalFunctions.GetDebugOptions("ShowInfo") ) then
		g_counterframe = g_counterframe + 1
		g_timecounter = g_timecounter + dt
		if (g_timecounter > 1) then
			InfoText.Text = GetVariables("CurrentGamePhase").." "..g_counterframe.."\r"..GetVariables("currentNavManager")
			--sur wii uniquement
			if (OPCore.GetPlatform() == "Wii") then
				local meminfo = OPWii.GetMemInfos()
				InfoText.Text = InfoText.Text.."\r MFL : "..string.sub((meminfo.low_total - meminfo.low_allocated),1,4)	
				InfoText.Text = InfoText.Text.."\r MFH : "..string.sub((meminfo.high_total - meminfo.high_allocated)	,1,4)
			end
			InfoText.Text = InfoText.Text.."\r LT : "..string.sub(g_lastloadtime,1,3).."s"
			--OPLog.Log("Display "..GlobalFunctions.Display(OPGraphic.GetVideoMemoryStatistics()))
			local tabgr = OPGraphic.GetVideoMemoryStatistics()
			local vidinfo = tabgr.total - tabgr.available
			InfoText.Text = InfoText.Text.."\r MemVid : "..string.sub(vidinfo,1,3)
			
			--pas vraiment utile
			--InfoText.Text = InfoText.Text.."\r Click "..Cursor.g_clickcompteur

			g_timecounter = 0
			g_counterframe = 0
		end
	end
	
	--un pdate spécifique selon ce qu'on souhaite faire
	if g_curupdatefct.fct ~= nil then
		g_curupdatefct.fct()
	end
	

	
	--[[if (OPCore.GetPlatform() == "Wii") then
		local s = "PadInfo 1 : "..Display(OPInput.GetPadInfos(1))
		s = "PadInfo 2 : "..Display(OPInput.GetPadInfos(2))
		InputText.Text = s		
	end
]]	
end

function IsActive()
	return g_active
end

function OnKeyUp(key)
	if GlobalFunctions.GetDebugOptions("ConsoleMode") == false then
		return
	end

	if not g_active then
		return
	end
	
	--rajout appell pour racourcir clavier direct
	if TestFunctions.OnShortcutOff ~= nil and TestFunctions.OnShortcutOff(key) then
		return
	end
	
end

function OnKeyDown(key)

	if GlobalFunctions.GetDebugOptions("ConsoleMode") == false then
		return
	end
	
	--OPLog.Log(key)
	--si c la touche console
	if key == 222 or key == KEY_F2 then
		g_active = not g_active
		g_displaytext.Enabled = g_active
		Load("ConsoleText0","Text").Text="Type in your command"
		Load("ConsoleText0","Text").Enabled = g_active
		return
	end
	
	if not g_active then
		return
	end
	
	--rajout appell pour racourcir clavier direct
	if TestFunctions.OnShortcutOn ~= nil and TestFunctions.OnShortcutOn(key) then
		return
	end
	
	
	if key == KEY_F1 then
		g_showhelp =  not g_showhelp
		UpdateInfo(g_currentkeywordtype)
	end
	
	
	if (g_currentcmd == nil) then
		g_currentcmd =""
	end
    
    local s = OPInput.KeycodeToChar(key)
    local l = string.len(s)
    local l1=string.len(g_currentcmd)
    
    if (key==KEY_BACK) then
        if l1 > 0 then
            g_currentcmd = string.sub(g_currentcmd, 1, l1-1)
        end
        g_displaytext.Text=g_currentcmd
        g_choosingbetweencompletionlist = false
        return false
    elseif (key==KEY_RETURN) then
        g_displaytext.Text=""
        parseCommand()
        g_currentcmd=''
        g_choosingbetweencompletionlist = false
        return false
    elseif (key == KEY_TAB or key == KEY_SPACE) then
        AutoCompletion()
        return false
    end

    if (l==0 or key==KEY_ESCAPE) then
        return false
    else
        g_currentcmd=g_currentcmd..s
        g_choosingbetweencompletionlist = false
    end
    g_displaytext.Text=g_currentcmd
	
	if (key == KEY_NUMPAD2) then
		g_curselection = math.min(g_curselection +1,LINENB)
		UpdateTextColor()
	end
	if (key == KEY_NUMPAD8) then
		g_curselection = math.max(g_curselection -1,0)
		UpdateTextColor()
	end
	
end

--c'est le onkeydown en simplifié
function OnPadButtonDown(pad,button)
	if button == WPAD_DOWN then
		--OPLog.Log("console : down")
		g_curselection = math.min(g_curselection +1,LINENB)
		UpdateTextColor()
	end
	if button == WPAD_UP then
		--OPLog.Log("console : up")
		g_curselection = math.max(g_curselection -1,0)
		UpdateTextColor()
	end
	
	if button == WPAD_PLUS then
		g_curselection = 0
		UpdateTextColor()
		g_active = not g_active
		--OPLog.Log("on active la console"..tostring(g_active))
		g_showhelp = true
		g_displaytext.Enabled = g_active
		Load("ConsoleText0","Text").Enabled = g_active
		if g_active then
			Load("ConsoleText0","Text").Text = "Chose your command"
			g_waitingforarg = false
			g_currentkeywordtype = "function"
			UpdateInfo(g_currentkeywordtype)
		else
			for i=1,LINENB do
				Load("ConsoleText"..i,"Text").Enabled = false
			end
		end
	end
	
	if button == WPAD_MINUS then
		g_currentcmd = g_commandwiicache[g_curselection]
		OPLog.Log("cmd "..g_currentcmd)
		g_showhelp = true
		parseCommand()
		g_curselection = 0
		
	end

	return false
end

-------------------------------------------------------
-- pas necessaire depuis la version 1.5
--OPLua.Include("Framework/TestFunctions.lua")
-------------------------------------------------------

function AutoCompletion()
    --on regarde si on est mode choix dans la liste
    if g_choosingbetweencompletionlist then
        g_indexincompletionlist = math.mod(g_indexincompletionlist + 1,table.getn(g_CurrentCompletionList))
        g_currentcmd = g_CurrentCompletionList[g_indexincompletionlist+1]
        g_displaytext.Text=g_currentcmd
        return
    end
    --sinon
    --on parcourt le fonction Parsing, et on compléte la fonction
    --si possible 
    g_CurrentCompletionList = {}
    
    --on teste les keywords
    for i,tab in pairs(TestFunctions.g_Keywords) do
        if string.find(tab.name,g_currentcmd) then
			if (g_currentkeywordtype == tab.fct) then
				table.insert(g_CurrentCompletionList,tab.name)
			end
        end
    end    

    if (table.getn(g_CurrentCompletionList)>0) then
        g_currentcmd=g_CurrentCompletionList[1]
        g_displaytext.Text=g_currentcmd
        g_choosingbetweencompletionlist = true    
        g_indexincompletionlist = 0
    end
end

----------------------------------------------

function parseCommand()
    if g_waitingforarg then
		OPLog.Log("rajout de "..g_currentcmd.." à argtable "..g_curfctcall.nbarg)
        table.insert(g_argtable,g_currentcmd)
        if table.getn(g_argtable) == g_curfctcall.nbarg then
            g_curfctcall.fct()
            g_waitingforarg = false
			if (OPCore.GetPlatform()=="PC")	then		
				UpdateInfo("function")
			else
				OnPadButtonDown(1,WPAD_PLUS)
			end
		else
			UpdateInfo(g_currentcmd)
        end
			
    else
		if Shortcut(g_currentcmd) then
			return
		end
        if TestFunctions.FunctionParsing[g_currentcmd] ~= nil then
            if TestFunctions.FunctionParsing[g_currentcmd].nbarg == 0 then
                TestFunctions.FunctionParsing[g_currentcmd].fct()
				if (OPCore.GetPlatform()=="PC")	then		
					UpdateInfo("function")
				else
					OnPadButtonDown(1,WPAD_PLUS)
				end
            else
                g_argtable={}
                g_waitingforarg = true
                g_curfctcall = TestFunctions.FunctionParsing[g_currentcmd]
				UpdateInfo(g_currentcmd)
            end
        end
    end
end

--on regarde si c'est un objet ou warp
function Shortcut(g_currentcmd)
	local ut= unit(g_currentcmd)
	
	--attention ça ne marche pas si les units ne sont pas dynamiques
	if ut ~= nil and (ut.ClassName == "SearchSite" or ut.ClassName == "Closeup") then
		g_argtable[1] = g_currentcmd
		TestFunctions.JumpTo() 
		return
	end
	
	local ut = unit("Inventory"..g_currentcmd,"InventoryObject")
	if ut ~= nil then
		g_argtable[1] = g_currentcmd
		TestFunctions.GetObject() 
		return
	end
	
	local ut = Load(g_currentcmd,"Cutscene",true)
	if ut ~= nil then
		StartCutscene(ut.Name,self)
	end	
end

function UpdateInfo(cmd)

	--OPLog.Log("updateinfo "..cmd)
	g_currentkeywordtype = cmd
	
	Load("ConsoleText0","Text").Text = cmd.." : "

	for i=1,LINENB do
		Load("ConsoleText"..i,"Text").Enabled= false
	end
	
	if g_showhelp then
		local compteur = 1
		for u,tab in pairs(TestFunctions.g_Keywords) do
			if (tab.fct == cmd and tab.shortcut == nil and (OPCore.GetPlatform()=="PC" or tab.onwii or g_waitingforarg) and compteur <= LINENB) then
				local text = Load("ConsoleText"..compteur,"Text")
				g_commandwiicache[compteur] = tab.name
				--text.cmd = cmd --on stocke la commande ici
				local s = ""
				--s = s..cmd.." : "
				s = s..tab.name
				--OPLog.Log("text "..compteur.." "..cmd.." "..tab.name)
				if tab.aide ~= nil then
					--s = s.." | "..tab.aide --on le vire finalement -> on utilise la doc pdf
				end
				text.Text = s
				text.Enabled = true
				compteur = compteur+1
			end
		end
	else 
		Load("ConsoleText0","Text").Text = "Press F1 for help"
	end

end

function CreateTextLine(linenb)
	--créer une ligne de texte sur la wii
	local ut = OPUnitFactory.CreateUnit("Text")
	ut.Font = Font_Default
	ut.Layer = LayerPopupDebug
	ut.Name = "ConsoleText"..linenb	
	ut.Position_Y = math.mod(linenb,LINEBYCOLLUMN) * LINESPACING
	ut.Position_X = math.floor(linenb/LINEBYCOLLUMN) * COLWIDTH
	ut.Scale_X = 0.8
	ut.Scale_Y = 0.8
	ut.Color.r = 255
	ut.Color.g = 255
	ut.Color.b = 255
	ut.Enabled = false
	ut.CharSpacing = -1
	ut.EditorFolder = "Debug\\"
end



function OnPadButtonUp(pad,button)
	--OPLog.Log(" on pad button up  "..pad.." "..button)
end


function SetUpdateFct(fct)
	AssertPopup(type(fct) == "function" , "prob param")
	
	if g_curupdatefct.fct == nil then
		g_curupdatefct.fct = fct
	else
		g_curupdatefct.fct = nil
	end
end

