local name, addon = ...
local modulname = 'char'
local events = {}
local modul = {
	['name'] = modulname
}
local L = LibStub("AceLocale-3.0"):GetLocale(name, true)
local function scanChar()
	local itemlist = {}
	local empty = true
	for i=1,19 do
		local id = GetInventoryItemID("player", i)
		if(id) then
			empty = false
			itemlist[id] = itemlist[id] or {}
			itemlist[id]['count'] = (itemlist[id]['count'] or 0) + 1
			addon:getName(id)
		end
	end
	return empty and nil or itemlist
end
local function bagLoop(id,res)
	local dName = modulname.."Count"
	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
					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) + b['count']
						end
					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["Equip %s"],b[desc])
		sum = sum + b[desc]					
	end
	return input,sum
end
function events:UNIT_INVENTORY_CHANGED(event,...)
	local playerID = addon.getPID()
	if(playerID) then
		modul['db'][playerID][0] = scanChar(nil)
	end
end
function events:ITEM_UNLOCKED(event,...)
	local playerID = addon.getPID()
	if(playerID) then
		modul['db'][playerID][0] = scanChar(nil)
	end
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
function modul:Enable()
	self.status = true
	local list = {}
	for event,func in pairs(events) do
		list[#list+1] = event
	end
	self.frame = addon:RegisterFunc(list,"OnEvent",OnEvent)
	OnEvent(self.frame,"UNIT_INVENTORY_CHANGED")
end
function modul:Disable()
	self.status = false
	for event,func in pairs(events) do
		self.frame:UnregisterEvent(event)
	end
end
addon['inits'][#addon['inits']+1] = function()
	modul.db,modul.status = addon:RegisterModul(modul, modulname)
	if(modul.status) then
		modul:Enable()
	end
end