.namespace SearchSite


g_utbackground = {}

-- g_launchingcard = {}



g_screenname = ""


function OnEnable()
	--OPLog.Log("OnEnable classe"..self.Name)
	--pas forcément trés propre ça :
	SetVariables("currentNavManager",self.Name)
	SetVariables("last_SearchSite",self.Name)
	
	-- Sauvegarde
	ProfilConfig.Set("Profil"..ProfilConfig.Get("CurrentProfil").."_lastscreen",self.Name)
	SaveManager.saveProfile()
	SaveManager.saveGame("Profil"..ProfilConfig.Get("CurrentProfil"))
	
	local shortname = string.gsub(self.Name,"_SearchSite","")

	InitSceneState(shortname)
	
	InitInterface(shortname)
	
	g_screenname = string.lower(string.gsub(self.Name,"_SearchSite",""))
	
	
	
	
	g_utbackground = OPUnitFactory.GetUnit(g_screenname.."_background","Background")
	
	AssertPopup(g_utbackground ~= nil ,"prob sur background "..g_screenname.."_background")
	local argsbuildobject = {[3]=g_utbackground,[1]=g_utbackground,[2]=g_utbackground, [0]=g_utbackground} -- temporaire

	ObjectManager.BuildObjects(g_screenname,argsbuildobject)
	
	
	AssertPopup(type(OFFSETX) == 'number' , "erreur constante non définie ")
	


	g_cursor = Load("Cursor","Cursor")
	
	g_horizdir = "none"
	g_vertdir = "none"
	
	-- self.speed = SCROLLSPEED
	
	self.alllistdonetextplayed = false -- on le met pas dans un datarray, c'est pas vital
	
	-- g_launchingcard = {}
	-- GetAllLaunchingCard(argsbuildobject)
	
	if self.OnUpdate == nil then
		OPLog.Log("attention le onupdate est pas défini sur "..self.Name)
		return
	end
	
	self.OnUpdate()


	
	--en config mini on vire les particules
	-- if ProfilConfig.Get("UseMinConfig") then
		-- for ind,ut in pairs(g_utforegroundtab) do
			-- ApplyToChildren(ut,DisablePart)
		-- end
	-- end
		
end

function DisablePart(ut)
	if ut.ClassName == "Particle2DEmitter" then
		ut.Enabled = false
	end
end

function RestartObjectList()
	if not ObjectManager.SearchActivated() then
		for i=1,5 do
			
			if SampleLevel.IsRegistered(g_screenname.."_search_"..i) and SampleLevel.IsEqual(g_screenname.."_search_"..i,"started") then
				ObjectManager.LaunchNewResearch(g_screenname,i)
				
				return
			end
		end		
	end
end



-- function GetAllLaunchingCard(tabbackground)
	-- --for u, background in pairs(tabbackground) do
		-- --ApplyToChildren(background,AddBackLaunchingCard)
	-- --end
-- -- end

-- function AddBackLaunchingCard(ut)
	-- if ut.ClassName == "LaunchingCard" then
		-- table.insert(g_launchingcard,ut)
	-- end
-- end

function OnDisable()
	--on clean les objets dynamiques
	-- -> important que le disable soit fait avant le enable suivant
	ApplyToClass("Object",OPUnitFactory.CloseUnit)

	--on vire la recherche en cours
	ObjectManager.CleanOldUnit()
	
	SubtitlesDisplay.HideSubtitles()
	
	--on fait un clean des blinking
	-- ApplyToClass("Animation",CloseBlink)
	
	-- on fait un clean des particules de highlight qui remplacent les blinks
	-- ApplyToClass("ParticlesHighlightObjects",CloseFx)
	ApplyToClass("Sparkle",OPUnitFactory.CloseUnit)
	
	--sécurité on close les takeobjecteffect particules
	ApplyToClass("TakeObjectEffect",OPUnitFactory.CloseUnit)
	
	--on ferme par sécurité les menus
	LeftInventory.CloseInventory()
	
	
	LeftInterface.Enabled = false
	

end

function CloseBlink(ut)
	if string.find(ut.Name,"blinkfor_") then
		OPUnitFactory.CloseUnit(ut)
	end
end

function CloseFx(ut)
	if string.find(ut.Name,"fxfor_") then
		OPUnitFactory.CloseUnit(ut)
	end
end


function InitInterface(shortname)
	--on remet l'interface
	Cursor.SetVisible(true)
	interfaceclsp.Enabled = false
	if DebugOptions.interfaceVersion == 2 then
		if LeftInterface.Enabled == false then
			LeftInterface.Enabled = true
		else
			-- LeftInventory.UpdateVignettes()
			LeftLocations.UpdateVignettes()
		end
	else -- ANCIENNE INTERFACE
	
		
	end

	

end



function OnUpdate(dt)
	if not IsEqualVariables("CurrentGamePhase","SearchSite") and not IsEqualVariables("CurrentGamePhase","Tutorial")  then
		return
	end


	-- UpdateScroll(dt)
	
	if self.UpdateUnit then
		self.UpdateUnit(dt)
	end
	
	--on attend d'avoir la "main" avant de lancer ce texte 
	-- if IsEqualVariables("CurrentGamePhase","SearchSite") and self.alllistdonetextplayed == false 
		-- and not ObjectManager.SearchActivated() 
		-- and SubtitlesBox.Flags_Visible == false and GetVariables("scrollingactive") 
		-- and self.CondSpecificToFinish()
		-- then --le scrolling active est pour les écrans sombres
		-- local res= false
		-- for u,ut in pairs(g_launchingcard) do
			-- res = res or ut.active
		-- end
		
		-- if not res then --aucune carte active
			-- local n = math.random(3)
			-- -- DisplaySimpleText("liste_complete0"..n)
			-- self.alllistdonetextplayed = true
		-- end
	-- -- end
	
	--tempo !!
	-- if obj_01_batte ~= nil then
		-- ConsoleText0.Text = ComputeObjVisibility(obj_01_batte)
	-- end
end



function CondSpecificToFinish()
	if self.assertpopupdone == nil then
		AssertPopup(false, " la fonction CondSpecificToFinish() n'est pas implémenté sur "..self.Name)
	end
	
	self.assertpopupdone = true
	return true
end


--gestion scrolling à externaliser sans doute
-- function UpdateScroll(dt)
    -- --on fait bêtement avec les flêches pour l'instant ?
   -- -- if g_horizdir == "left" then
	-- --	g_utmiddleground.Position_X = math.min(g_boundmiddleground.max , g_utmiddleground.Position_X + self.speed)
	-- --elseif g_horizdir == "right" then
	-- --	g_utmiddleground.Position_X = math.max(g_boundmiddleground.min , g_utmiddleground.Position_X -self.speed)
	-- --end
   
  -- --  g_utmiddleground.Position_Y = g_utmiddleground.InitPosY

	-- --UpdateParallax()
-- end

function UpdateParallax()
	--OPLog.Log("middl "..tostring(g_utmiddleground.Name))


end

function OnEnter_Gen()

	InventoryManager.OnEnterSearchSite()
	
	--on relance la liste do'bjet s'il y en avait une, et si il n'y pas déjà actuellement
	RestartObjectList()
	
	if self.OnEnter ~= nil then
		self.OnEnter()
	end
	
end

function OnTutoEnd()
	OnEnter_Gen()
end

function StartScroll(x)
	self.startx = x
	
	--on fait que sur la droite
	--if self.startx < (MINRANGEFROMBOUND+OFFSETX) then
	--	self.startx = MINRANGEFROMBOUND+OFFSETX
	--end
	
	if self.startx > (WIDTH_SCREEN-MINRANGEFROMBOUND) then
		self.startx = WIDTH_SCREEN-MINRANGEFROMBOUND
	end
	
end


-- function UpdateScrollByCursor(x)
	-- if x == self.startx then 
		-- return
	-- end
	
	-- local dist = math.abs(x-self.startx)
	-- local sign = (x-self.startx)/ dist
	
	-- g_horizdir = ""
	
	-- if dist > STARTSCROLLRANGE then
		-- if sign > 0 then
			-- g_horizdir = "right"
		-- else
			-- g_horizdir = "left"
		-- end
		
		-- self.speed = ((math.min(dist,MAXSCROLLRANGE) -STARTSCROLLRANGE)  / (MAXSCROLLRANGE - STARTSCROLLRANGE))  --coeff qui va de 0 à 1 
		-- self.speed = (1-self.speed) * SCROLLSPEED + (self.speed*MAXSCROLLSPEED)
	-- end
-- end
-- function StopScroll()
	-- g_horizdir = ""
-- end

function InitSceneState(shortname)
	UserData.Set(shortname.."_discovered",true)
	if SCREENGROUP == nil then
		return
	end
	--OPLog.Log("InitSceneState")
	--OPLog.Log("nb groupes = "..table.getn(SCREENGROUP))
	local nbgroups = table.getn(SCREENGROUP)

	local actualgroup = nil
	
	for numgroup=1,nbgroups do
		local nbscenesingroup = table.getn(SCREENGROUP[numgroup])
		for scene=1,nbscenesingroup do
			if "s"..string.format("%.2d",SCREENGROUP[numgroup][scene]) == shortname then
				actualgroup = numgroup
				break
			end
		end
		if actualgroup ~= nil then
			break
		end
	end
	
	AssertPopup((actualgroup ~= nil) , "erreur scene n'apartient à aucun groupe")
	
	
	for numgroup=1,nbgroups do
		local nbscenesingroup = table.getn(SCREENGROUP[numgroup])
		for scene=1,nbscenesingroup do
			if numgroup ~= actualgroup and UserData.Get("s"..string.format("%.2d",SCREENGROUP[numgroup][scene]).."_discovered") then
				UserData.Set("s"..string.format("%.2d",SCREENGROUP[numgroup][scene]).."_discovered",false)
			end
		end
	end
end


-- -- DEFINITIONBESTMIDDLEGROUNDPOS = 10

-- function FindBestMiddleGroundPosition(obj)
	-- local formerpos = g_utmiddleground.Position_X
	
	-- local step = (g_boundmiddleground.max - g_boundmiddleground.min) / DEFINITIONBESTMIDDLEGROUNDPOS
	-- local bestpos = 0
	-- local bestres = 0
	-- for i = 0,DEFINITIONBESTMIDDLEGROUNDPOS do
		-- local curpos = g_boundmiddleground.min + i * step
		-- g_utmiddleground.Position_X = curpos
		-- UpdateParallax()
		-- local res = ComputeObjVisibility(obj)
		-- --OPLog.Log(" res obj "..tostring(res).." "..obj.Name)
		-- --on peut le plus visible, ou le plus proche de la position actuelle
		-- if res > bestres or (res ==  bestres and (math.abs(formerpos - curpos) < math.abs(formerpos - bestpos)))  then
			-- bestres = res
			-- bestpos = curpos
		-- end
	-- end
	
	-- g_utmiddleground.Position_X = formerpos
	-- UpdateParallax()
	
	-- return bestpos,bestres
-- end

TESTDEFINITION = 3

--renvoit un chiffre qui indique à quel point l'objet est visible
function ComputeObjVisibility(obj)
	local vec = GetScreenCenter(obj)

	local stepwidth = obj.Dimension_Width / (2*TESTDEFINITION)
	local stepheight = obj.Dimension_Height / (2*TESTDEFINITION)
	
	local res = 0
	for i = -TESTDEFINITION,TESTDEFINITION do
		for j= -TESTDEFINITION,TESTDEFINITION do
			local x = vec.x + i *stepwidth
			local y = vec.y + j * stepheight
			
			if ( x >= 0 and x <= WIDTH_SCREEN and y >=0 and y <= HEIGHT_SCREEN) then
				local list = Cursor.ComputeOrderedUnitsAt(x,y)
				if list[1]~= nil and list[1].Name == obj.Name then
					res = res + 1
				end
			end
		end
	end

	return res
end
