-- LUALOCALS < ---------------------------------------------------------
local get_mod_api, minetest, piredo_player, piredo_schems, startswith
    = get_mod_api, minetest, piredo_player, piredo_schems, startswith
-- LUALOCALS > ---------------------------------------------------------

local api = get_mod_api()
local modstore = minetest.get_mod_storage()

local playing
local fading
local function stopmusic(id)
	if playing ~= id then return end
	minetest.sound_fade(playing, 1, 0)
	playing = nil
	fading = nil
end
local function fademusic()
	if fading or not playing then return end
	minetest.sound_fade(playing, 1/15, 0)
	local id = playing
	fading = id
	minetest.after(15, function()
			if playing == id then playing = nil end
			if fading == id then fading = nil end
		end)
end
local function startmusic()
	if playing then return end
	local id = minetest.sound_play("piranesi_intense", {gain = 0.25})
	playing = id
	minetest.after(105, function() stopmusic(id) end)
end

local oldroom
local function roomclass(player)
	local room, roompos, roommax = api.get_current_room()
	if not room then return end

	local margin = oldroom == room and 0.5 or 2.5
	local pos = player:get_pos()
	if pos.x - margin < roompos.x or pos.z - margin < roompos.z
	or pos.x + margin > roommax.x or pos.z + margin > roommax.z
	then return end
	oldroom = room

	local schem = piredo_schems[room]
	if schem and not schem.noscore then
		piredo_player.discover("room:" .. room)
	end

	if room == "special_blocked" then return end
	if startswith(room, "normal_") or startswith(room, "quad_")
	then return "normal" end

	return room
end

piredo_player.register_playerstep(function(player)
		local class = roomclass(player)
		if not class then return fademusic() end

		local key = "music_played_" .. class
		if modstore:get_string(key) ~= "" then return end
		modstore:set_string(key, "true")

		startmusic()
	end)
