--[[
	Returns a random vector3 within a region3, that has a clear area around it of specified size. This function yields.
]]

local random = Random.new(tick())

return function(region, clearAreaSize)
	local position

	local regionPosition = region.CFrame.Position

	while not position do
		local minX, maxX =
			regionPosition.X - (region.Size.X / 2) + clearAreaSize.X,
			regionPosition.X + (region.Size.X / 2) - clearAreaSize.X
		local minY, maxY =
			regionPosition.Y - (region.Size.Y / 2) + clearAreaSize.Y,
			regionPosition.Y + (region.Size.Y / 2) - clearAreaSize.Y
		local minZ, maxZ =
			regionPosition.Z - (region.Size.Z / 2) + clearAreaSize.Z,
			regionPosition.Z + (region.Size.Z / 2) - clearAreaSize.Z

		local x, y, z = random:NextNumber(minX, maxX), random:NextNumber(minY, maxY), random:NextNumber(minZ, maxZ)

		local clearRegionMax, clearRegionMin = Vector3.new(x, y, z) + clearAreaSize, Vector3.new(x, y, z) - clearAreaSize

		local area = Region3.new(clearRegionMax, clearRegionMin)

		local partsInArea = workspace:FindPartsInRegion3(area, nil, 1)

		if #partsInArea == 0 then
			position = Vector3.new(x, y, z)
		end
		wait()
	end

	return position
end
