local C = Broker_Everything.color


-- Function to determine the total number of bag slots and the number of free bag slots.
local function BagsFreeUsed()
	local t = GetContainerNumSlots(0)
	local f = GetContainerNumFreeSlots(0)

	for i=1,NUM_BAG_SLOTS do
		local idtoinv = ContainerIDToInventoryID(i)
		local il = GetInventoryItemLink("player", idtoinv)
		if il then
			local st = select(7, GetItemInfo(il))
			if st ~= "Soul Bag"
					and st ~= "Ammo Pouch"
					and st ~= "Quiver" then
				t = t + GetContainerNumSlots(i)
				f = f + GetContainerNumFreeSlots(i)
			end
		end
	end
	return f, t
end

local bags_onevent = function(self)
	local f, t = BagsFreeUsed()
	local u = t - f
	local txt = u .. "/" .. t
	local c = C.white

	if Broker_EverythingDB.bag_display == 0 then
		txt = u .. "/" .. t
	elseif Broker_EverythingDB.bag_display == 1 then
		txt = (t - u) .. " free"
	end

	if (u / t) > 0.9 then
		c = C.red
	elseif (u / t) > 0.7 then
		c = C.dkyellow
	end

	-- self.obj.text = c (txt)
        (self.obj or LibStub:GetLibrary("LibDataBroker-1.1"):GetDataObjectByName(L[Bags])).text = c (txt)
end


local bags_events = {
	"PLAYER_LOGIN",
	"BAG_UPDATE",
	"UNIT_INVENTORY_CHANGED",
}


local bags_onclick = function(self, btn)
	if btn == "RightButton" then
		if Broker_EverythingDB.bag_display == 0 then
			Broker_EverythingDB.bag_display = 1
		else
			Broker_EverythingDB.bag_display = 0
		end
		bags_onevent(self)
	else
		ToggleBackpack()
	end
end


local bags_tooltip = function(t)
	local f, total = BagsFreeUsed()
	t:AddLine(L["Bags"])
	t:AddLine(" ")
	t:AddDoubleLine(C.white(L["FREESLOTS"] .. " :"), C.white(f))
	t:AddDoubleLine(C.white(L["TOTALSLOTS"] .. " :"), C.white(total))
	t:AddLine(" ")
	t:AddLine(C.dkgreen(string.format("%s", L["BAGHINTLEFT"])))
	t:AddLine(C.dkgreen(string.format("%s", L["BAGHINTRIGHT"])))
end


Broker_Everything:Register(L["Bags"],
	--GetItemIcon(17966),
	"Interface\\Addons\\Broker_Everything\\media\\INV_Misc_Bag_08",
	0,
	bags_onevent,
	bags_events,
	bags_onclick,
	bags_tooltip,
	nil,
	nil)
