-- LUALOCALS < ---------------------------------------------------------
local ch_colours, ch_player_api, ipairs, math, string, table, tostring
	= ch_colours, ch_player_api, ipairs, math, string, table, tostring
local math_floor, string_gsub, table_concat
	= math.floor, string.gsub, table.concat
-- LUALOCALS > ---------------------------------------------------------

local function resize(n)
	return "^[resize:" .. n .. "x" .. n
end
local function txesc(s)
	return string_gsub(string_gsub(tostring(s), "%^", "\\^"), ":", "\\:")
end

local barres = 32
local pad = 1

ch_util.register_playerstep(function(player, data)
		local meta = player:get_meta()

		if not data.hudsel then
			data.hudsel = true
			player:hud_set_hotbar_selected_image("hopbar_sel.png")
		end

		local colours = ch_player_api.get_colours(player)
		local list = {}
		for i, k in ipairs(ch_colours.by_num) do
			if colours[k] then list[#list + 1] = i end
		end

		local lstr = table_concat(list, ",")
		if lstr ~= data.list then
			data.list = lstr
			player:hud_set_hotbar_itemcount(#list)

			local txr = {"[combine:", (#list * barres + pad * 2),
				"x", barres + pad * 2}
			for i = 1, #list do
				txr[#txr + 1] = ":"
				txr[#txr + 1] = (i - 1) * barres + pad
				txr[#txr + 1] = ","
				txr[#txr + 1] = pad + math_floor(barres / 2)
				txr[#txr + 1] = "="
				txr[#txr + 1] = txesc(ch_colours.colour_name(list[i])
					.. ".png^[noalpha" .. resize(barres)
					.. "^[mask:hopbar_mask.png"
					.. "^[opacity:160")
			end
			player:hud_set_hotbar_image(table_concat(txr))
		end

		local col = meta:get_int("colour")
		local wcol = list[player:get_wield_index()] or 1
		if wcol ~= col then
			meta:set_int("colour", wcol)
			col = wcol
			ch_player_api.set_colour(player, ch_colours.colour_name(col))
		end
	end)
