
.namespace NavigationManager

g_roomtoblink = {} --pas besoin de sauvegarder
m_previous_manager = nil
g_utnotify = nil
g_unit_source = nil
g_destinationname = nil

g_curmusic = nil

function OnEnable()
	NavigationManager.switch_state = 0
end

--on vérifie pour l'alpha et aussi pour les particules
function PrepareAlphaCompareAndAlphaTreshold(screen)
	ApplyToChildren(screen,CheckBackground)
end

--plus d'actualités
--on ne l'appelle que si l'on n'est pas la résolution native
function CheckAlphaTreshold(ut)
	if ut.ClassName == "SpriteGameplay" or ut.ClassName == "Animation" then
		if SPRITEGAMEPLAYALPHATRESHOLD ~= nil and SPRITEGAMEPLAYALPHATRESHOLD[ut.Name] ~= nil then
			ut.AlphaTestThreshold = SPRITEGAMEPLAYALPHATRESHOLD[ut.Name]
		end
	end
end

-- on change ces attributs AVANT de les charger sinon ils ne sont pas pris en compte
-- on met le visuel avec alpha progressif, et par contre on peut cliquer à travers 
function CheckBackground(ut)
--si on est en réso native, on met le testtreshold à 0 sinon on le met à 100
	if ut.ClassName == "Background" then --on pourra toujours mettre le nointercept à true
		ut.AlphaCompare = 240
		--if GlobalFunctions.cur_width == WIDTH_SCREEN and GlobalFunctions.cur_height == HEIGHT_SCREEN then
		ut.AlphaTestThreshold = 0
		
		-- avec le nouveau tool de didier on a plus ce probléme
		
		-- else
			-- if BACKGROUNDALPHATRESHOLD ~= nil and BACKGROUNDALPHATRESHOLD[ut.Name] ~= nil then
				-- ut.AlphaTestThreshold = BACKGROUNDALPHATRESHOLD[ut.Name]
			-- else
				-- ut.AlphaTestThreshold = 230
			-- end
			
			-- ApplyToChildren( ut , CheckAlphaTreshold)
		-- end
		
		-- ApplyToChildren( ut , CheckStartDelay)
		
		

	end
end

MINSTARTDELAYFORPARTICLES = -10

--on vérifie le startdelay AVANT leur laoding comme ça il est trés rapide
function CheckStartDelay(ut)
	if ut.ClassName == "Particle2DEmitter" then
		if ut.StartDelay < MINSTARTDELAYFORPARTICLES then --on met pas plus de 10s de délai
			OPLog.Log("attention la particule ".. ut.Name .." a trop de start delay ! ")
			ut.StartDelay = MINSTARTDELAYFORPARTICLES
		end
	end
end

-- ------------------------------------------------------------------------
--  Switch function
-- ------------------------------------------------------------------------
function SwitchTo(source,destination,utnotify)
	
	 -- if(destination=="Menu_Start") then
	 -- Search_Inventory.Enabled = false
	 -- end
	
	OPLog.Log("appel de switch to "..self.Name)
	AssertPopup((type(destination) == "string" or type(destination) == "table") , "erreur params destination switchto" )
	AssertPopup((source == nil or type(source) == "table") , "erreur params source switchto" )
	AssertPopup(GetVariables("CurrentGamePhase") ~= "Transition" , "prob switch manager déjà lancé ")
	
    if (source == nil) then
        if (GetCurrentManager() ~= nil) then
            source = GetCurrentManager()
        end
    end
    if (source == nil) then
        m_previous_manager = nil
    else
        m_previous_manager = source
    end
    g_unit_source = source
	
	if type(destination) == "table" then
		g_destinationname = destination.Name
	else
		g_destinationname = destination
	end
	
	g_utnotify = utnotify
	
    NavigationManager.switch_state = 0
	
	if not IsEqualVariables("CurrentGamePhase","Cutscene") then
		SetVariables("CurrentGamePhase","Transition")
		EnableRemotePointerGen( 1, false )
	end
	
	FadeOut.Enabled = true
	FadeOut.UnitNotify = NavigationManager
	FadeOut.Start()
	
	--sécurité 
	FadeIn.Enabled = false
	
	--on arrête le oneliners en cours si besoin
	SoundPlayer.StopCurrentVoice()
	
	if source.OnLeave ~= nil then
		source.OnLeave()
	end
	
	-- if unit(g_destinationname).ClassName == "Closeup" then
		-- --PlaySoundEffect("int_closeup01")
	-- end
end

function DisableSource()
	--OPLog.Log("disable source "..g_unit_source.Name)
	--TODO groupe à remettre en place ensuite
	
	--[[local groupesource = GetGroupName(g_unit_source.Name)
	local groupedest = GetGroupName(g_destinationname)
	
	--à filtrer en fonction de l'existence du Pak
	if OPCore.GetPlatform() == "Wii" then
		local tab = OPFileManager.FindFiles("paks/"..g_unit_source.Name..".oppak")
		if table.getn(tab) > 0 then
			OPLog.Log("on Décharge pak "..g_unit_source.Name)
			OPPak.UnloadPak(g_unit_source.Name)
		end
		--OPLog.Log("fin décharge pak")
	end]]
	
	g_unit_source.Enabled = false
	
	--Disable(g_unit_source)
	--[[if (groupesource~= "" and groupesource ~= groupedest) then
		OPLog.Log("on unload "..groupesource)
		OPFileManager.UnloadGroup(groupesource)
		g_roomtoblink = {} --pour pas que le roomtoblink soit trop gros
	end]]
	
end

--nous donne le grop name en fonction du nom
function GetGroupName(unitname)
	--plus d'actualités
	--[[if string.find(unitname,"Menu") then
		return ""
	end
	
	if string.find(unitname,"V0") then
		local levelnumber = string.sub(unitname,3,3)
		OPLog.Log("levelnumber "..levelnumber)
		return "Village0"..levelnumber
	elseif string.find(unitname,"_S") then --est ce que c'est un niveau ?
		local diznumber=string.sub(unitname,2,2)
		local levelnumber = string.sub(unitname,3,3)
		if diznumber=="0" then
			return "Level0"..levelnumber
		else
			return "Level"..(10+tonumber(levelnumber))
		end
	else
		return ""
	end]]
	
	return ""
end

function LoadDestination()
	-- SearchInterface.Enabled = false
	
	
	
	--à filtrer en fonction de l'existence du Pak
	if OPCore.GetPlatform() == "Wii" then
		local tab = OPFileManager.FindFiles("paks/"..g_destinationname..".oppak")
		if table.getn(tab) > 0 then
			OPLog.Log("on charge pak "..g_destinationname)
			OPPak.LoadPak(g_destinationname)
		end
	end
	
	--TODO pas de groupe pour l'instant
	--[[if unit(g_destinationname)== nil then
		--on charge le groupe opl correspondant
		OPLog.Log("loaddestination : "..g_destinationname)
		local groupname = GetGroupName(g_destinationname)
	
		if groupname ~= "" then
			OPFileManager.LoadGroup(groupname)
		end
	end]]
	
	local dest = OPUnitFactory.GetUnit(g_destinationname)
	--si c'est tj nul
	if (dest== nil) then
		AssertPopup(false, "unit pas valide , lors du switch")
		return
	end
	
	if dest.ClassName == "SearchSite" then
		PrepareAlphaCompareAndAlphaTreshold(dest)
	end

	
	SetCurrentManager(dest)
	
	
	dest.Enabled = true

	SoundPlayer.StopAllAmbiances()
	UpdateCurrentAmbiance(dest.Name)
	UpdateMusic(dest)
	--SoundPlayer.PlayAmbiance( g_Ambiance[g_destinationname] )
	
	-- Met le curseur générique
	Cursor.ChangeCursor(CURSOR_GENERIQUE)
	
	--on sauvegarde si c'est un nouveau écran de village ou de site de fouille ou de carte
	--[[local t = OPTime.GetTime()
	if (dest.ClassName == "Excavation_Site" or dest.ClassName == "Village_Site" ) and DebugOptions.UseMenu then
		g_profconf.Set(g_userdata.Get("UserName").."_lastscreen",dest.Name)

		g_saveman.saveProfile()
		g_saveman.saveGame(g_userdata.Get("UserName"))
		
		OPLog.Log("temptotal sauvegarde "..string.sub(tostring(OPTime.GetTime() - t),1,5))
	end]]
end

-- -----------------------------------------------------------------------
--  On end fader handler
-- ------------------------------------------------------------------------
function OnFaderEnd()
	--OPLog.Log("switch state "..tostring(self.switch_state))
	
	
	
	if (NavigationManager.switch_state == 0) then
        -- end of fade in
		NavigationManager.switch_state = 1
		
		FadeOut.Enabled = false
		--SoundPlayer.StopAllAmbiances()
		
		--UpdateCurrentMusic( g_destinationname )
		
		if (g_unit_source  ~= nil) then --on l'apple aprés updatecurrentmusic
			DisableSource()
        end

        --OPLog.Log("on a fait disable source ")
		
		local t = OPTime.GetTime()
		LoadDestination()
		
		OPLog.Log("temps chargement de "..g_destinationname.." : "..(OPTime.GetTime()-t))
		
		if TestCenter.ParentEnabled then
			TestCenter.SetLastLoadTime((OPTime.GetTime()-t))
		end		
		--OPLog.Log("testcenter mis à jour ")
		
       	FadeIn.UnitNotify = NavigationManager
		FadeIn.Enabled = true
		FadeIn.Start()		
		OPLog.Log("on relance le fade ".. "fadin "..tostring(FadeIn.Enabled).." fadeout "..tostring(FadeOut.Enabled))
    elseif (NavigationManager.switch_state == 1) then
		-- end of fade out	
		FadeIn.Enabled = false
		FinishSwitch()
	else
		AssertPopup(false, "etat bizarre de switch_state")
	end
end

function FinishSwitch()
	--OPLog.Log("fin switch ")
	if not IsEqualVariables("CurrentGamePhase","Cutscene") then
		if OPUnitFactory.GetUnit(g_destinationname).Opl == "interfacemenu" or OPUnitFactory.GetUnit(g_destinationname).Opl == "newinterface" then
			SetVariables('CurrentGamePhase',"Menu")
		elseif OPUnitFactory.GetUnit(g_destinationname).Opl == "map" then
			SetVariables('CurrentGamePhase',"Closeup")			
		elseif g_destinationname == "VideoPlayer" then
			SetVariables('CurrentGamePhase',"Video")
		else
			SetVariables("CurrentGamePhase",OPUnitFactory.GetUnit(g_destinationname).ClassName)
		end
	end
		
	if IsEqualVariables("CurrentGamePhase", "SearchSite")
	or IsEqualVariables("CurrentGamePhase", "Closeup") 
	or g_destinationname == "VideoPlayer"
	then
		OPUnitFactory.GetUnit(g_destinationname).OnEnter_Gen()
	end
				
	if g_utnotify ~= nil and type(g_utnotify)=="table" then
		g_utnotify.OnSwitchEnd(g_destinationname)
	end
	
	OPLua.CallGC()
end

function DisableAllInterface()

end


function EnableAllInterface()
	
end


-- ------------------------------------------------------------------------
--  Return to Previous manager
-- ------------------------------------------------------------------------
function RestorePreviousManager()
    SwitchTo(GetCurrentManager(),m_previous_manager)
end

-- ------------------------------------------------------------------------
--  Get previous manager
-- ------------------------------------------------------------------------
function GetPreviousManager()
    return m_previous_manager
end

-- ------------------------------------------------------------------------
--  Set current manager
-- ------------------------------------------------------------------------
function SetCurrentManager(ut_Val)
	OPLog.Log("set de currentman "..ut_Val.Name)
	SetVariables("currentNavManager",ut_Val.Name)
end



function UpdateCurrentAmbiance( managerName )
	--on arrête l'ambiance en cours si elle est différente de celle de l'écran suivant
	if m_previous_manager ~= nil
			and not IsEqualVariables('CurrentAmbiance',"") 
			and not IsEqualVariables('CurrentAmbiance', g_Ambiance[g_destinationname].soundTab[1])
	then
		SoundPlayer.StopAmbiance(GetVariables('CurrentAmbiance'))
	end
	
	if IsEqualVariables("CurrentAmbiance","") and g_Ambiance[g_destinationname] ~= nil then
		SoundPlayer.PlayAmbiance(g_Ambiance[g_destinationname])
	end
end


function OnSoundEnd(name,failed)
	if failed == true then
		OPLog.Log("erreur sur la musique ! ")
		return
	end

	if type(g_Music[g_destinationname]) == "string" then
		SoundPlayer.PlayMusic(g_Music[g_destinationname], true, true, NavigationManager)
	else
		local idCurrentSound = GetCurrentSoundID()
		local nextSoundID = GetNextSoundID(idCurrentSound)
		
		SoundPlayer.PlayMusic(g_Music[GetVariables("currentNavManager")][nextSoundID], true, false, NavigationManager)
	end
end

function GetCurrentSoundID()
	for i, soundName in ipairs( g_Music[g_destinationname] ) do
		if soundName == GetVariables("CurrentMusic") then
			return i
		end
	end
	
	return 0
end

function GetNextSoundID(currentID)
	if currentID == 0 or currentID == table.getn(g_Music[g_destinationname]) then
		return 1
	end
	
	return currentID + 1
end

function GetDestinationName()
	if g_destinationname ~= nil then
		return g_destinationname
	else
		return ""
	end
end

function GetDestinationName()
	if g_destinationname ~= nil then
		return g_destinationname
	else
		return ""
	end
end

SOUNDFADESPEED = 0.02

function UpdateMusic(dest)
	
	if g_curmusic ~= nil then
		OPLog.Log("update music "..dest.Name.." "..tostring(g_Music[dest.Name]).." "..tostring(g_curmusic.Name))
	end
	if g_Music ~= nil and g_Music[dest.Name]~= nil and unit(g_Music[dest.Name]).Enabled == false then
		unit(g_Music[dest.Name]).Enabled = true
		unit(g_Music[dest.Name]).Volume = 0
		SoundFader.Fade(unit(g_Music[dest.Name]),SOUNDFADESPEED,ProfilConfig.Get("VolumeMusic") / 100) --TODO rendre le volume compatible avec les options
		
		if g_curmusic ~= nil then
			SoundFader.Fade(g_curmusic,SOUNDFADESPEED,0,self)
		end
		
		g_curmusic = unit(g_Music[dest.Name])
	end
end

function OnSoundFadeEnd(soundut)
	soundut.Enabled = false
end