hud_set_api = {}

local huds = {} --stores tables of hud element ids

local registered_sets = {}

--remove stored hud ids of leaving players
minetest.register_on_leaveplayer(function(player)
		huds[player:get_player_name()] = nil
	end)

local emptyflags = {}
function hud_set_api.register_set(name, set)
	--Try to verify correctness of hud set using assertions on types
	local err = "Error registering hud set: "
	assert(not registered_sets[name],
		"There is already a hud set with name " .. name .. " registered.")
	for k, v in pairs(set)
	do
		assert(type(k) == "number" or k == "flags",
			err ..
			"Keys of set table must be numbers or 'flags', got " ..
			type(k) .. " " .. (type(k) == "string" and k or ""))
		assert(type(v) == "table",
			err ..
			"Expected array of tables, got " ..
			type(v))
	end
	set.flags = set.flags or emptyflags
	for k, v in pairs(set.flags)
	do
		assert(type(k) == "string",
			err ..
			"table in flags field must only contain strings as keys, got " ..
			type(k))
		assert(type(v) == "boolean" or type(v) == "nil",
			err ..
			"table in flags field must only contain boolean or nil values, got " ..
			type(v))
	end
	
	registered_sets[name] = set
end

function hud_set_api.set_set(player, set_name)
	local set = registered_sets[set_name]
	assert(set, "Error: tried to set an unknown hud set.")
	local playername = player:get_player_name()
	local hud = huds[playername]
	if not hud --create hud table
	then
		hud = {}
		huds[playername] = hud
	else --remove current hud
		for i, id in ipairs(hud)
		do
			player:hud_remove(id)
			hud[i] = nil
		end
	end
	
	for i, v in ipairs(set)
	do
		table.insert(hud, player:hud_add(v))
	end
	player:hud_set_flags(set.flags)
end
