lzr_messages = {}

local message_handles = {}
local message_timers = {}

function lzr_messages.show_message(player, text, duration)
	local playername = player:get_player_name()
	local id
	if message_handles[playername] then
		id = message_handles[playername]
		player:hud_change(id, "text", text)
	else
		id = player:hud_add({
			hud_elem_type = "text",
			position = { x = 0.5, y = 0.5 },
			name = "message",
			text = text,
			number = 0xFFFFFF,
			alignment = { x = 0, y = -1 },
			offset = { x = 0, y = -32 },
			scale = { x = 100, y = 100 },
			size = { x = 3, y = 3 },
			z_index = 0,
		})
	end
	message_handles[playername] = id
	message_timers[playername] = duration
	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)
