--Weighting of Sounds

function AudioUtils.PickWeightedRandomSound(instance: Instance)
	local children = instance:GetChildren()
	local total = 0
	for _, sound in pairs(children) do
		total += sound:GetAttribute("Weight") or 1
	end
	-- total is now the sum of all weights
	--print(total)

	local choice = rng:NextNumber(0, total)
	-- choice is some number between 0 and total; sounds with larger weights take up more space in that range
	local threshold = 0
	for _, sound in pairs(children) do
		threshold += sound:GetAttribute("Weight") or 1
		if choice < threshold then
			return sound -- return the sound whose weight range contains the choice
		end
	end
	-- we should never end up here, but just in-case, we'll fallback to regular randomness
	return children[rng:NextInteger(1, #children)] 
end

function AudioUtils.PlayOneShot(obj, folder, part)
	local attachment = Instance.new("Attachment", part)
	---"This adorn adds a part for debugging purposes"--
	---local adorn = Instance.new("SphereHandleAdornment", attachment)
	---adorn.Adornee = part
	---adorn.Radius = 20
	local halfSize = part.Size / 2
	local x = rng:NextNumber(-halfSize.X, halfSize.X)
	local y = rng:NextNumber(-halfSize.Y, halfSize.Y)
	local z = rng:NextNumber(-halfSize.Z, halfSize.Z)
	attachment.Position = Vector3.new(x, y, z)
	---adorn.CFrame = attachment.CFrame

	local clone = AudioUtils.PickWeightedRandomSound(folder):Clone()
	clone.Parent = attachment
	--print(tagName .. ": cloned sound ")

	local playbackRange = obj:GetAttribute("PlaybackSpeed")
	local volumeRange = obj:GetAttribute("Volume")
	clone.PlaybackSpeed = rng:NextNumber(playbackRange.Min, playbackRange.Max)
	clone.Volume = rng:NextNumber(volumeRange.Min, volumeRange.Max)
	clone.Ended:Connect(function()
		--print(tagName .. ": destorying attachment")
		attachment:Destroy() 
	end)

	clone:Play()
end

return AudioUtils
