local AiDetectionSystem = inherited("AiDetectionSystem", SystemMap)

function AiDetectionSystem:new()
	local ms = instance(self)
	return ms
end

function AiDetectionSystem:wants(ent)
	return ent.aspects.ai_detection
end

function AiDetectionSystem:ent_added(ent)	
	--print("ad")
end

function AiDetectionSystem:ent_removed(ent)	
	--assert(false)
end

function AiDetectionSystem:step(dt)
	local world = self.world

	local team_target_system = world:get_system_by_key("team_ai_target")	
	if world then
		for ent, _ in pairs(self.ents) do
			--print("JS")
			if ent.ai_scan_delay > 0 then
				ent.ai_scan_delay = ent.ai_scan_delay - dt				
			else
				local team = ent.team
				if team then

					local best_target = nil
					local best_dist2 = nil	

					for _, enemy_team in ipairs(team:get_enemy_teams()) do
						local target_map = team_target_system:get_target_map(enemy_team)
						if target_map then
							
							local x,y = ent.x,ent.y					
							local radius = ent.radius + ent.ai_detection_range
							for target, _ in pairs(target_map) do
								local target_radius = target.radius
								local threshold2 = (radius+target_radius)^2
								local dist2 = math.distance2(x, y, target.x, target.y)
								--print(dist2, threshold2)
								if dist2 < threshold2 then
									if not best_dist2 or dist2 < best_dist2 then
										if not world.universe:is_line_of_sight_blocked(x,y, target.x, target.y) then
											best_dist2 = dist2
											best_target = target										
										end
									end
									--HIT
								end
							end
						end
					end

					if best_target ~= ent.ai_target then
						ent:set_ai_target(best_target)
					end
				end
				ent.ai_scan_delay = 1 + math.random()
			end
		end
	end
end

return AiDetectionSystem