local _, ns = ...
local B, C, L, DB = unpack(ns)

--[[背包整理从左到右
/run C_Container.SetSortBagsRightToLeft(false)
背包整理从右到左
/run C_Container.SetSortBagsRightToLeft(true)
拾取物品从右到左
/run C_Container.SetInsertItemsLeftToRight(false)
拾取物品从左到右
/run C_Container.SetInsertItemsLeftToRight(true)]]

local function updateBagSortDirection(reverse)
	C_Container.SetSortBagsRightToLeft(reverse)
	C_Container.SetInsertItemsLeftToRight(reverse)
end

local function hookReverseBagSort(button)
	if not button or button.__OrzUIReverseBagSort then return end
	button.__OrzUIReverseBagSort = true
	button:RegisterForClicks("LeftButtonUp", "RightButtonUp")
	button:HookScript("PreClick", function(_, btn)
		updateBagSortDirection(btn ~= "RightButton")
	end)
	button:HookScript("OnEnter", function()
		if button.__OrzUITooltipAdded then return end
		button.__OrzUITooltipAdded = true
		GameTooltip:AddLine("左键：正向整理 右键：逆向整理", 1, 1, 1)
		GameTooltip:Show()
	end)
	button:HookScript("OnLeave", function()
		button.__OrzUITooltipAdded = nil
	end)
end

local function setupReverseBagSort()
	hookReverseBagSort(_G.BagItemAutoSortButton)
	hookReverseBagSort(_G.BankItemAutoSortButton)
end

local eventFrame = CreateFrame("Frame")
eventFrame:RegisterEvent("PLAYER_LOGIN")
eventFrame:RegisterEvent("BAG_UPDATE")
eventFrame:SetScript("OnEvent", setupReverseBagSort)

if not C.Infobar.Bags then return end

local module = B:GetModule("Infobar")
local info = module:RegisterInfobar("Bags", C.Infobar.BagsPos)
		
info.eventList = {
	"BAG_UPDATE",
	"PLAYER_LOGIN",
}

info.onEvent = function(self)
	setupReverseBagSort()

	local free = 0
	for i = 0, NUM_BAG_SLOTS do
		free = free + C_Container.GetContainerNumFreeSlots(i)
	end
	self.text:SetText("|cff00cccc"..free)
end

info.onEnter = function(self)
  local free, total, used = 0, 0, 0
		for i = 0, NUM_BAG_SLOTS do
			free, total = free + C_Container.GetContainerNumFreeSlots(i), total + C_Container.GetContainerNumSlots(i)
		end
		used = total - free
	GameTooltip:SetOwner(self, "ANCHOR_TOP", 0, 6);
	GameTooltip:ClearAllPoints()
	GameTooltip:SetPoint("BOTTOM", self, "TOP", 0, 1)
	GameTooltip:ClearLines()
	GameTooltip:AddLine(L["Bags"].." : "..used.."/"..total,0,.6,1)
	--GameTooltip:AddLine(" ")
	GameTooltip:AddLine("左键正向整理，右键逆向整理", 1, 1, 1)
	--GameTooltip:AddLine()
	--GameTooltip:AddDoubleLine(L["Total"]..":",,.6,.8,1, 1, 1, 1)
	--GameTooltip:AddDoubleLine(L["Used"]..":",,.6,.8,1, 1, 1, 1)
	GameTooltip:Show()
end

info.onLeave = function() GameTooltip:Hide() end
info.onMouseUp = function(_, btn) ToggleAllBags() end