music = {}

music.tracks = {
	{name = "jahzzar_cddc_aisles", length = 216, title = "Aisles", author = "Jahzzar", license = "CC-BY-SA"},
	{name = "jahzzar_cddc_deadpanned", length = 274, title = "Deadpanned", author = "Jahzzar", license = "CC-BY-SA"},
	{name = "jahzzar_cddc_mantra", length = 176, title = "Mantra", author = "Jahzzar", license = "CC-BY-SA"},
	{name = "jahzzar_cddc_pure", length = 246, title = "Pure", author = "Jahzzar", license = "CC-BY-SA"},
	{name = "jahzzar_cddc_siste_viator", length = 118, title = "Siste Viator", author = "Jahzzar", license = "CC-BY-SA"},
}

music.delay = 5
music.last_played = 0
music.handles = {}

function music.display_song_info(song)
	local message = music.tracks[song].title .. " by " .. music.tracks[song].author .. ", " .. music.tracks[song].license
	minetest.chat_send_all(message)
end

function music.stop()
	for _, player in ipairs(minetest.get_connected_players()) do
		local handle = music.handles[player:get_player_name()]
		if handle then
			minetest.sound_stop(handle)
		end
	end
end

function music.play_to_all(sound_spec)
	-- Play the song to each player, store the handle in meta
	for _, player in ipairs(minetest.get_connected_players()) do
			local player_name = player:get_player_name()
			local sound_spec2 = sound_spec
			sound_spec2.to_player = player_name
			sound_spec2.gain = sound_spec.gain or player:get_meta():get_float("music:gain")

		local handle = minetest.sound_play(sound_spec2)
		music.handles[player_name] = handle
	end
end

function music.play()
	-- Randomly choose a different track
	local choose
	repeat
		choose = math.random(1, #music.tracks)
	until choose ~= music.last_played

	local sound_spec = {name = music.tracks[choose].name}
	music.play_to_all(sound_spec)
	music.display_song_info(choose)

	music.last_played = choose
end

minetest.register_on_newplayer(function(player)
	player:get_meta():set_float("music:gain", 0.1)
	player:get_meta():set_int("music:handle", 0)
end)

-- Delete Handle When Player Leaves
minetest.register_on_leaveplayer(function(player, timed_out)
	music.handles[player:get_player_name()] = nil
end)

minetest.register_chatcommand("volume", {
	description = "Set music volume.",
	params = "<float >= 0>",
	func = function(name, param)
		if tonumber(param) and tonumber(param) >= 0 and minetest.get_player_by_name(name) then
			minetest.get_player_by_name(name):get_meta():set_float("music:gain", tonumber(param))
			return true, "Music volume set to " .. param .. "."
		else
			return false, "Invalid usage, see /help volume."
		end
	end,
})

util.register_on_tod(ikea.opening_time, function()
	music.stop()
	music.play()
end)

util.register_on_tod(12, music.play)
util.register_on_tod(ikea.closing_time-2, music.play)

util.register_on_tod(ikea.closing_time, function()
	music.stop()
	music.play_to_all({
		name = "ikea_night",
		gain = 0.8,
	})
end)
