lzr_messages = {}

local message_handles = {}
local message_timers = {}

--[[
Show a on-screen message in the center to a player for a given time.
If there is already a message shown, it will be replaced.

* player: ObjectRef of player
* text: Text to display
* duration: Duration in seconds
* color: Text color (as hexadecimal RGB number) (default: 0xFFFFFF)

Returns the HUD ID of the message on success
]]
function lzr_messages.show_message(player, text, duration, color)
	local playername = player:get_player_name()
	local id
	if not color then
		color = 0xFFFFFF
	end
	if message_handles[playername] then
		id = message_handles[playername]
		player:hud_change(id, "text", text)
		player:hud_change(id, "number", color)
	else
		id = player:hud_add({
			type = "text",
			position = { x = 0.5, y = 0.5 },
			name = "message",
			text = text,
			number = color,
			alignment = { x = 0, y = -1 },
			offset = { x = 0, y = -32 },
			scale = { x = 100, y = 100 },
			size = { x = 3, y = 3 },
			z_index = 100,
		})
	end
	if id then
		message_handles[playername] = id
		message_timers[playername] = duration
	end
	return id
end

minetest.register_on_leaveplayer(function(player)
	message_handles[player:get_player_name()] = nil
	message_timers[player:get_player_name()] = nil
end)

minetest.register_globalstep(function(dtime)
	local players = minetest.get_connected_players()
	for p=1, #players do
		local name = players[p]:get_player_name()
		if message_timers[name] then
			message_timers[name] = message_timers[name] - dtime
			if message_timers[name] <= 0 then
				players[p]:hud_remove(message_handles[name])
				message_handles[name] = nil
				message_timers[name] = nil
			end
		end
	end
end)
