lzr_ambience = {}

local S = minetest.get_translator("lzr_ambience")

local ambiences = {}

local current_singleplayer_ambience = nil -- ambience sound handler. nil if no current ambience
local current_singleplayer_ambience_id = nil -- ambience type ID (e.g. "ocean", "temple"). nil if uninitialized
local ambience_active = true

lzr_ambience.register_ambience = function(id, soundname, gain)
	ambiences[id] = { soundname = soundname, gain = gain }
end

function lzr_ambience.stop_ambience()
	if current_singleplayer_ambience then
		minetest.sound_stop(current_singleplayer_ambience)
		current_singleplayer_ambience = nil
	end
end

function lzr_ambience.set_ambience(id, no_play)
	local ambience = ambiences[id]
	if not ambience then
		minetest.log("error", "[lzr_ambience] set_ambience called with invalid ambience ID ("..tostring(id)..")")
		return false
	end
	minetest.log("info", "[lzr_ambience] Ambience set to: "..tostring(id))
	-- No-op if we already have this ambience active
	if current_singleplayer_ambience_id == id and current_singleplayer_ambience then
		return true
	end
	lzr_ambience.stop_ambience()
	if id ~= "none" and not no_play and ambience_active then
		current_singleplayer_ambience = minetest.sound_play({name=ambience.soundname}, {gain = ambience.gain, to_player="singleplayer", loop=true})
	end
	current_singleplayer_ambience_id = id
	return true
end

lzr_ambience.register_ambience("ocean", "lzr_ambience_ocean", 0.08)
lzr_ambience.register_ambience("temple", "lzr_ambience_temple", 1.0)
-- Special ambience that is completely silent
lzr_ambience.register_ambience("none")

local setting = minetest.settings:get_bool("lzr_ambience_start_with_ambience", true)

minetest.register_on_joinplayer(function(player)
	if setting then
		ambience_active = true
		lzr_ambience.set_ambience("ocean")
	else
		ambience_active = false
		lzr_ambience.set_ambience("ocean", true)
	end
end)

minetest.register_chatcommand("ambience", {
	description = S("Toggle ambience sounds"),
	func = function()
		if current_singleplayer_ambience then
			ambience_active = false
			lzr_ambience.stop_ambience()
			return true, S("Ambience sounds disabled.")
		else
			ambience_active = true
			lzr_ambience.set_ambience(current_singleplayer_ambience_id)
			return true, S("Ambience sounds enabled.")
		end
	end,
})
