-- LUALOCALS < ---------------------------------------------------------
local ipairs, piredo_api
    = ipairs, piredo_api
-- LUALOCALS > ---------------------------------------------------------

local api = piredo_api.get_mod_api()

local hotbarsize = 1

local function resize_hotbar(player, oldsize, newsize)
	player:hud_set_hotbar_itemcount(newsize)
	if newsize > 0 and oldsize == 0 then
		player:hud_set_flags({hotbar = true})
	elseif oldsize > 0 and newsize == 0 then
		player:hud_set_flags({hotbar = false})
	end
end

local function check_hotbar(player)
	local slack = 1
	local needsize = 0
	local inv = player:get_inventory()
	for idx, stack in ipairs(inv:get_list("main")) do
		if not stack:is_empty() then
			needsize = idx + slack
		else
			slack = 0
		end
	end

	local widx = player:get_wield_index()
	if needsize > 0 and widx > needsize then
		needsize = widx
	end

	if needsize ~= hotbarsize then
		resize_hotbar(player, hotbarsize, needsize)
		hotbarsize = needsize
	end
end

api.register_playerstep(check_hotbar)

api.register_on_playerswap(function(newp, oldp)
		if oldp then oldp:hud_set_flags({hotbar = false}) end
		if newp then resize_hotbar(newp, 0, hotbarsize) end
	end)
