local TeamBulletSystem = inherited("TeamBulletSystem", SystemMap)

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

function TeamBulletSystem:wants(ent)
	return ent.aspects.team_bullet and ent.aspects.team_owned
end

function TeamBulletSystem:ent_added(ent)
end

function TeamBulletSystem:ent_removed(ent)
end

function TeamBulletSystem:step(dt)
	local world = self.world
	local team_target_system = self.world:get_system_by_key("team_target")	
	if team_target_system then
		for ent, _ in pairs(self.ents) do
			local team = ent.team
			if team then			
				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
						local best_target = nil
						local best_dist2 = nil
						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
									best_dist2 = dist2
									best_target = target
								end
								--HIT
							end
						end
						if best_target then		
							ent.impact_target = best_target					
							ent.any_impact = true							
						end
					end
				end
			end
		end
	end
end

return TeamBulletSystem