-- Enemy spawn system

for _,area in pairs(workspace.Areas:GetChildren()) do
	local function RefillEnemies()
		local function SpawnEnemy(spawnRegion)
			local enemyToSpawn = spawnRegion.EnemiesToSpawnHere:GetChildren()[math.random(1,#spawnRegion.EnemiesToSpawnHere:GetChildren())].Name
			local xVectorRandom = spawnRegion.CFrame.RightVector * spawnRegion.Size.X * (math.random(-50, 50) / 100)
			local yVectorRandom = spawnRegion.CFrame.UpVector * spawnRegion.Size.Y * (math.random(-50, 50) / 100)
			local zVectorRandom = spawnRegion.CFrame.LookVector * spawnRegion.Size.Z * (math.random(-50, 50) / 100)
			local spawnPosition = spawnRegion.Position + xVectorRandom + yVectorRandom + zVectorRandom
			require(enemyFunctions).SpawnEnemy(enemyToSpawn, spawnPosition, area.Enemies)
		end
		local enemyCounts = {}
		for _,enemy in pairs(area.Enemies:GetChildren()) do
			if not enemyCounts[enemy.Name] then
				enemyCounts[enemy.Name] = 1
			else
				enemyCounts[enemy.Name] = enemyCounts[enemy.Name] + 1
			end
		end
		for _,spawnRegion in pairs(area.SpawnRegions:GetChildren()) do
			local enemiesInRegion = 0
			for _,enemyToSpawn in pairs(spawnRegion.EnemiesToSpawnHere:GetChildren()) do
				if enemyCounts[enemyToSpawn.Name] then
					enemiesInRegion = enemiesInRegion + enemyCounts[enemyToSpawn.Name]
				end
			end
			for i = 1, spawnRegion.MaximumEnemies.Value - enemiesInRegion do
				SpawnEnemy(spawnRegion)
			end
		end
	end
	if area:FindFirstChild("Enemies") and area:FindFirstChild("SpawnRegions") then
		RefillEnemies()
		area.Enemies.ChildRemoved:Connect(RefillEnemies)
	end
end
