local name, addon = ...
local modulname = 'guildbank'
local events = {}
local modul = {
	['name'] = modulname,
	['typ'] = 'guild'
}
local GuildBankIsOpen = false
local failCount = 0
local lgbc
local function gbagLoop(id)
	local res = {}
	local dName = modulname.."Count"
	for k,v in pairs(modul['db']) do
		local guilds = addon:getGuilds()
		if(guilds[k]) then
			local guildID = addon.getGID()
			if(guildID and guilds[k]['faction']==guilds[guildID]['faction'] or not guildID) then
				local guildname = guilds[k]['name']
				for bag,list in pairs(v) do
					for a,b in pairs(list) do
						if(a == id) then
							res[guildname] = res[guildname] or {
								[dName] = 0
							}
							res[guildname][dName] = res[guildname][dName] or 0
							res[guildname][dName] = res[guildname][dName] + b['count']
						end
					end
				end
			end
		end
	end
	return res
end
function modul.Search2(id,res,mode)
	local guildID = addon.getGID()
	if(guildID) then
		modul['db'][guildID] = modul['db'][guildID] or {}
	end
	res = res or {}
	for guildname, b in pairs(gbagLoop(id)) do
		if(mode) then
			res[#res+1] = format(" %s: %s",addon:colorize(guildname,"00ffff"),addon:colorize(b[modulname..'Count'],"ffffff"))
		else
			res[#res+1] = format("%s %s: %s",addon:getIcon(id),guildname,addon:colorize(b[modulname..'Count'],"ffffff"))
		end
	end
	return res
end
local function scanGuildBank(tab)
	if(not tab) then return end
	local itemlist = {}
	for slot = 1,98 do
		local texturePath, itemCount, locked, isFiltered = GetGuildBankItemInfo(tab,slot)
		if(itemCount>0) then
			local itemLink = GetGuildBankItemLink(tab,slot)
			if(itemLink) then
				local id = addon:getItemId(itemLink)
				if(id) then
					itemlist[id] = itemlist[id] or {}
					itemlist[id]['count'] = itemlist[id]['count'] or 0
					itemlist[id]['count'] = itemlist[id]['count'] + itemCount
					addon:getName(id)
				end
			end
		end
	end
	local count = 0
	for k,v in pairs(itemlist) do
		count = count + 1
	end
	if(count==0 and failCount<3) then
		C_Timer.After(.2, function(tab) scanGuildBank(tab) end)
		failCount = failCount + 1
		return
	end
	failCount = 0
	return count==0 and nil or itemlist
end
function events:GUILDBANKBAGSLOTS_CHANGED(event,...)
	if(not addon.checkGID() or not GuildBankIsOpen) then return end
	local tab = GetCurrentGuildBankTab()
	if(tab>0) then
		local guildID = addon.getGID()
		if(guildID) then
			local list = scanGuildBank(tab)
			if(list) then
				modul['db'][guildID][tab] = list
			end
		end
	end
end
function events:GUILDBANKFRAME_CLOSED(event,...)
	GuildBankIsOpen = false
end
function events:GUILDBANKFRAME_OPENED(event,...)
	GuildBankIsOpen = true
end
local function OnEvent(self,event,...)
	local guildID = addon.getGID()
	if(guildID and type(events[event])=='function') then
		modul['db'] = addon:GetNamespace(modul.name)
		modul['db'][guildID] = modul['db'][guildID] or {}
		events[event](self, event, ...)
	end
end
local function lgbc_scan(page)
	local guildID = addon.getGID()
	if(guildID and page) then
		local itemlist = {}
		for slot, link, stack in lgbc:IteratePage(page) do
			local id = addon:getItemId(link)
			if(id) then
				itemlist[id] = itemlist[id] or {}
				itemlist[id]['count'] = itemlist[id]['count'] or 0
				itemlist[id]['count'] = itemlist[id]['count'] + stack
				addon:getName(id)
			end
		end
		modul['db'][guildID][page] = itemlist
	end
end
local function lgbc_scanAll()
	for page = 1, lgbc:GetNumBankTabs() do
		lgbc_scan(page)
	end
end
function modul:OnPageSync(event, sender, page, guildName)
--	print(event, sender, page, guildName)
	local guildID = addon.getGID()
	lgbc_scan(page)
end
function modul:Delete(id, typ)
	self['db'] = addon:GetNamespace(modul.name)
	if(typ == self['typ'] and id and id>0) then
		self['db'][id] = nil
	end
end
function modul:Enable()
	if(not addon:IsClassic()) then
		self.status = true
		local list = {}
		for event,func in pairs(events) do
			list[#list+1] = event
		end
		--[[ 暫時修正
		lgbc = LibStub("LibGuildBankComm-1.0",true)
		if(lgbc) then
			lgbc.RegisterCallback(self,"GuildBankComm_PageUpdate", "OnPageSync")
		end
		--]]
		self.frame = addon:RegisterFunc(list,"OnEvent",OnEvent)
	else
		self.status = false
	end
end
function modul:Disable()
	self.status = false
	if(not addon:IsClassic()) then
		for event,func in pairs(events) do
			self.frame:UnregisterEvent(event)
		end
		if(lgbc) then
			lgbc.UnregisterCallback(self, "GuildBankComm_PageUpdate")
		end
	end
end
addon['inits'][#addon['inits']+1] = function()
	modul.db,modul.status = addon:RegisterModul(modul, modulname)
	if(modul.status) then
		modul:Enable()
	end
end