GuildBankCycler = ZO_Object:Subclass()

function GuildBankCycler:New()
	return ZO_Object.New(self)
end

GUILDBANKCYCLER = GuildBankCycler:New()

GuildBankCycler.guildCount = 0
GuildBankCycler.dropDownLookup = {}
GuildBankCycler.dropDownIndex = {}

-- You know what's weird? These Layer Pushed combos, that's what. Guild panel seems to be some combination of the below. 4/4 is guild bank/shop
local layers = {
    [22] = true,
    [23] = true,
    [24] = true,
    [44] = true,
    [62] = true,
    [63] = true,
    [64] = true,
    [82] = true,
    [83] = true,
    [84] = true,
}

local currentSelector = nil

function GuildBankCycler:SelectorPushed(...)
	local eventId, a, b = ...
    if not (layers[a*10 + b]) then return end

	local control = (not ZO_SelectGuildBankDialogGuild:IsHidden() and ZO_SelectGuildBankDialogGuild)
					or
					(not ZO_SelectTradingHouseGuildDialogGuild:IsHidden() and ZO_SelectTradingHouseGuildDialogGuild)
                    or
                    (not ZO_GuildSelector:IsHidden() and ZO_GuildSelectorComboBox)
					or nil

	if not control then return end

	local dropDown = control.m_comboBox
	local entries = dropDown:GetItems()

	self.guildCount = #entries
	self.dropDownLookup[control] = {}
	self.dropDownIndex[control] = {}
	for index,entry in ipairs(entries) do
		self.dropDownLookup[control][entry.guildId or self.guildCount] = entry
		self.dropDownIndex[control][index] = entry.guildId or self.guildCount
		if entry.guildText or entry.selectedText == dropDown:GetSelectedItem() then currentSelector = index end
	end
end

function GuildBankCycler:ChangeGuildSelected(control, _, delta)
	if delta < 0 then
		if currentSelector < self.guildCount then
			currentSelector = currentSelector + 1
		else
			if currentSelector == self.guildCount then
				currentSelector = 1
			end
		end
	else
		if currentSelector > 1 then
			currentSelector = currentSelector - 1
		else
			if currentSelector == 1 then
				currentSelector = self.guildCount
			end
		end
	end
	local entry = self.dropDownLookup[control][self.dropDownIndex[control][currentSelector]]
	entry:callback(entry, entry)
end



local function GuildBankCyclerLoaded(eventCode, addOnName)

	if(addOnName ~= "GuildBankCycler") then
        return
    end
	ZO_PreHookHandler(ZO_SelectGuildBankDialogModalUnderlay, "OnMouseWheel", function(...) GuildBankCycler:ChangeGuildSelected( ZO_SelectGuildBankDialogGuild, ...) end)
	ZO_PreHookHandler(ZO_SelectTradingHouseGuildDialogModalUnderlay, "OnMouseWheel", function(...) GuildBankCycler:ChangeGuildSelected( ZO_SelectTradingHouseGuildDialogGuild, ...) end)
	ZO_PreHookHandler(ZO_GuildSelectorComboBox, "OnMouseWheel", function(...) GuildBankCycler:ChangeGuildSelected( ZO_GuildSelectorComboBox, ...) end)
	EVENT_MANAGER:RegisterForEvent("GuildBankCyclerGuildSelector", EVENT_ACTION_LAYER_PUSHED, function(...) GuildBankCycler:SelectorPushed(...) end)
end

EVENT_MANAGER:RegisterForEvent("GuildBankCyclerLoaded", EVENT_ADD_ON_LOADED, GuildBankCyclerLoaded)