local name, addon = ...
local modulname = 'bank'
local events = {}
local modul = {
	['name'] = modulname
}
local L = LibStub("AceLocale-3.0"):GetLocale(name, true)
local BankIsOpen = false
function modul.Guess(id)
	local dbcount = modul.Get(id)
	local count = GetItemCount(id,true)
	local playerID = addon.getPID()
	local tt = false
	if(playerID and dbcount > count) then
		local dif = dbcount - count
		modul['db'][playerID] = modul['db'][playerID] or {}
		for bag=5,GetNumBankSlots()+4 do
			if(modul['db'][playerID][bag] and modul['db'][playerID][bag][id] and modul['db'][playerID][bag][id]['count']>0) then
				while(dif>0 and modul['db'][playerID][bag][id]['count']>0) do
					tt = true
					dif = dif - 1
					modul['db'][playerID][bag][id]['count'] = modul['db'][playerID][bag][id]['count'] - 1
					if(modul['db'][playerID][bag][id]['count'] == 0) then
						modul['db'][playerID][bag][id] = nil
					end
				end
			end
		end
	end
	if(tt) then
		addon:updateTT()
	end
end
local function guess(bag)
	if(bag) then
		for id, v in pairs(bag) do
			local _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _, isCraftingReagent = GetItemInfo(id)
			if(isCraftingReagent) then
				modul.Guess(id)
			end
		end
	end
end
local function scanAllBankBags(delayed)
	if(not addon:funcSync(scanAllBankBags,delayed)) then return end
	local playerID = addon.getPID()
	if(playerID) then
		modul['db'][playerID] = modul['db'][playerID] or {}
		for bag=5,GetNumBankSlots()+4 do
			if(BankIsOpen) then
				modul['db'][playerID][bag] = addon:scanBag(bag) -- loop all bought bankbags
			else
				guess(modul['db'][playerID][bag])
			end
		end
		if(BankIsOpen) then
			modul['db'][playerID][-1] = addon:scanBag(-1) -- Main bankbag
		else
			guess(modul['db'][playerID][-1])
		end
		modul['db'][playerID][-3] = addon:scanBag(-3) -- Main reagentbag
		for k,v in pairs(modul['db'][playerID]) do
			if(not(k==-1) and not(k==-3) and not(k>4 and k<=GetNumBankSlots()+4)) then
				modul['db'][playerID][k] = nil -- prevent bogus bankbags
			end
		end
		addon:updateTT()
	end
end
local function bagLoop(id,res)
	local cName = modulname.."Count"
	local dName = cName
	for k,v in pairs(modul['db']) do
		local units = addon:getUnits()
		if(units[k]) then
			local playerID = addon.getPID()
			if(playerID and units[k]['faction']==units[playerID]['faction']) then
				local unitname = units[k]['name']
				for bag,list in pairs(v) do
					if(bag == -3) then
						dName = 'reagentCount'
					else
						dName = cName
					end
					for a,b in pairs(list) do
						if(a == id) then
							res[unitname] = res[unitname] or {
								[dName] = 0
							}
							res[unitname][dName] = res[unitname][dName] or 0
							res[unitname][dName] = res[unitname][dName] + b['count']
						end
					end
				end
			end
		end
	end
	return res
end
function modul.Get(id)
	local cName = modulname.."Count"
	local dName = cName
	local res = 0
	local playerID = addon.getPID()
	for k,v in pairs(modul['db']) do
		if(playerID and k==playerID) then
			for bag,list in pairs(v) do
				for a,b in pairs(list) do
					if(a == id) then
						res = res + b['count']
					end
				end
			end
		end
	end
	return res
end

function modul.Search(id,res)
	local playerID = addon.getPID()
	if(playerID) then
		modul['db'][playerID] = modul['db'][playerID] or {}
	end
	return playerID and bagLoop(id,res) or res
end
function modul.Output(input,sum,b)
	local desc = modulname..'Count'
	if(b[desc] and b[desc]>0) then
		input[#input+1] = format(L["Bank %s"],b[desc])
		sum = sum + b[desc]					
	end
	desc = 'reagentCount'
	if(b[desc] and b[desc]>0) then
		input[#input+1] = format(L["Reagents %s"],b[desc])
		sum = sum + b[desc]					
	end
	return input,sum
end
function events:BANKFRAME_OPENED(event,...)
	BankIsOpen = true
	scanAllBankBags(nil)
end
function events:BANKFRAME_CLOSED(event,...)
	BankIsOpen = false
end
function events:PLAYERBANKBAGSLOTS_CHANGED(event,...)
	scanAllBankBags(nil)
end
function events:PLAYERBANKSLOTS_CHANGED(event,...)
	scanAllBankBags(nil)
end
function events:PLAYERREAGENTBANKSLOTS_CHANGED(event,...)
	scanAllBankBags(nil)
end
function events:ITEM_UNLOCKED(event,...)
	scanAllBankBags(nil)
end
local function OnEvent(self,event,...)
	local playerID = addon.getPID()
	if(playerID and type(events[event])=='function') then
		modul['db'] = addon:GetNamespace(modul.name)
		modul['db'][playerID] = modul['db'][playerID] or {}
		events[event](self, event, ...)
	end
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
local skipClassic = {
	['PLAYERREAGENTBANKSLOTS_CHANGED'] = true
}
function modul:Enable()
	self.status = true
	local list = {}
	for event,func in pairs(events) do
		if(not addon:IsClassic() or (addon:IsClassic() and not skipClassic[event])) then
			list[#list+1] = event
		end
	end
	self.frame = addon:RegisterFunc(list,"OnEvent",OnEvent)
end
function modul:Disable()
	self.status = false
	for event,func in pairs(events) do
		if(not addon:IsClassic() or (addon:IsClassic() and not skipClassic[event])) then
			self.frame:UnregisterEvent(event)
		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