--[[ script de gestion des rayons de lumière visibles dans certains écrans de sites de fouille --]]

.namespace LightrayManager

SCALE_MIN = 5	--valeur entière pour le random, en réalité 0.5
SCALE_MAX = 12	--valeur entière pour le random, en réalité 1.2

g_MoveLength = 0
g_FrameCount = 0

g_Speed = 0

g_PreviousScale = 0
g_NextScale = 0


function OnEnable()
	if g_TabLightray == nil then
		g_TabLightray = {}
	elseif g_TabLightray ~= {} then
		OPLog.Log("Erreur sur le tableau des lightray")
	end
end

function OnUpdate()
	Tick()
end

function Tick()
	for i, lightrayName in pairs( g_TabLightray ) do
		OPUnitFactory.GetUnit(lightrayName,"Lightray").Tick()
	end
end

function OnDisable()
	for i, lightrayName in pairs( g_TabLightray ) do
		local lightray = OPUnitFactory.GetUnit(lightrayName,"Lightray")
		if lightray~= nil then
			lightray.Enabled = false
		end
	end
	
	g_TabLightray = {}
end




function InitManager( p_nbRay, p_min_x, p_max_x, parentToApply, angle )
	local iterator = 0
	
	if parentToApply== nil then
		self.Enabled = false
		return
	end
	
	while iterator < p_nbRay do
		-- création de chaque rayon de lumière
		local ray = OPUnitFactory.CreateUnit('Lightray')
		ray.Parent = parentToApply
		ray.Name = ComputeRayName(iterator)
		ray.Enabled = true
		
		ray.Position_Y = -100
		ray.Position_X = math.random(p_min_x, p_max_x)
		
		ray.PositionMinX = math.max(p_min_x, ray.Position_X - 120)
		ray.PositionMaxX = math.min(p_max_x, ray.Position_X + 120)
		
		if math.abs(angle) > 0.01  then
			ray.Rotation = angle*math.pi/180
		end
		
		AddLightrayToTab( ray.Name )
		
		iterator = iterator + 1
	end
end


function ComputeRayName(id)
	local name = 'Lightray'
	
	if id >= 9 then
		name = name..(id+1)
	else
		name = name..'0'..(id+1)
	end
	
	return name
end


function ComputeNextScale()
    
	g_PreviousScale = self.Children[0].Scale_X
    g_NextScale = math.random(SCALE_MIN, SCALE_MAX) / 10
    
    g_Speed = math.random( 20, 60 ) / 10000
    
    g_MoveLength = math.abs(g_NextScale - g_PreviousScale)/g_Speed
    g_FrameCount = 0
    
end


function AddLightrayToTab( LightrayName )
	table.insert( g_TabLightray, LightrayName )
end

