-- LUALOCALS < ---------------------------------------------------------
local math, minetest, pairs
    = math, minetest, pairs
local math_random
    = math.random
-- LUALOCALS > ---------------------------------------------------------

local ambgroup = "ambiance"

minetest.register_abm({
		nodenames = {"group:" .. ambgroup},
		interval = 1,
		chance = 1,
		action = function(pos, node)
			local def = minetest.registered_items[node.name]
			local chance = minetest.get_item_group(node.name, "ambiance")
			if chance > 1 and math_random(1, chance) ~= 1 then return end

			local spec = def and def.sounds and (def.sounds.ambiance
				or def.sounds.footstep or def.sounds.dig or def.sounds.dug)
			if not spec then return end

			local param = {}
			for k, v in pairs(spec) do param[k] = v end
			param.pos = pos
			param.gain = (param.gain or 1) / 5
			param.max_hear_distance = 8
			minetest.after(math_random(), function()
					return minetest.sound_play(
						param.name, param, true)
				end)
		end
	})

local function setambiance(nodename, chance, soundname, gain)
	local def = minetest.registered_nodes[nodename]
	local groups = {}
	for k, v in pairs(def.groups) do groups[k] = v end
	groups.ambiance = chance or 1
	local sounds = {}
	for k, v in pairs(def.sounds) do sounds[k] = v end
	if soundname then
		sounds.ambiance = {
			name = soundname,
			gain = gain or 1
		}
	end
	return minetest.override_item(nodename, {groups = groups, sounds = sounds})
end

setambiance("piredo_terrain:default__water_source", 25)
setambiance("piredo_terrain:default__water_flowing", 5)
setambiance("piredo_terrain:default__lava_source", 10)
setambiance("piredo_terrain:default__lava_flowing", 5)
setambiance("piredo_terrain:piranesi__cauldron", 1, "xdecor_boiling_water")
setambiance("piredo_terrain:piranesi__cauldron_purple", 1, "xdecor_boiling_water")
setambiance("piredo_terrain:piranesi__cauldron_black", 1, "xdecor_boiling_water")
setambiance("piredo_terrain:piranesi__machine_gear_1_a", 5, "piredo_puzzles_sztest_gears")
setambiance("piredo_terrain:piranesi__machine_gear_2_a", 5, "piredo_puzzles_sztest_gears")
setambiance("piredo_terrain:fire__basic_flame", 10, "fire_small", 0.5)
setambiance("piredo_terrain:fire__permanent_flame", 10, "fire_small", 0.5)
