local addonName, addon = ...
local childName = addon['childName']
local child = addon[childName]
local events = child['events']
local db, dbf, dbr,dbp, scanned, realm
LibStub("zzHelper"):Embed(child)
local function prepareDB()
	local faction = UnitFactionGroup('player')
	realm = GetRealmName()
	local player = UnitName("player")
	addon['db']['profile'][childName] = addon['db']['profile'][childName] or {}
	db = addon['db']['profile'][childName]
	db[faction] = db[faction] or {}
	dbf = db[faction]
	dbf[realm] = dbf[realm] or {}
	dbr = dbf[realm]
	dbr[player] = dbr[player] or {
		['mail'] = 0,
		['mailunread'] = 0
	}
	dbp = dbr[player]
	child['db'] = db
	addon['callbacks']:Fire(format("Init%s", childName))
end
local function mailupdate()
	if(not scanned) then
		return dbp['mailunread'], dbp['mail']
	else
		local cur, tot = GetInboxNumItems()
		dbp['mail'] = tot
		return dbp['mailunread'], tot
	end
end
local function mail()
	local packageIcon, stationeryIcon, sender, subject, money, CODAmount, daysLeft, hasItem, wasRead, wasReturned, textCreated, canReply, isGM
	local index,newunread = 0,0
	local unread, tot = mailupdate()
	subject = "start"
	while(subject) do
		index = index + 1
		packageIcon, stationeryIcon, sender, subject, money, CODAmount, daysLeft, hasItem, wasRead, wasReturned, textCreated, canReply, isGM = GetInboxHeaderInfo(index)
		if(subject and not wasRead) then
			newunread = newunread + 1
			if(GetInboxNumItems() == 0 and scanned) then
				newunread = 0
			end
		end
	end
	if(not(dbp['mail'] > 0 and GetInboxNumItems() == 0)) then
		dbp['mailunread'] = newunread
	end
	if(dbp['newmail']) then
		if(HasNewMail() and tot == 0)  then
			tot = #{GetLatestThreeSenders()}
			if(scanned and select(2,GetInboxNumItems()) == 0) then
				tot = 0
			end
		end
		if(dbp['mailunread'] == 0) then
			dbp['mailunread'] = 1
		end
		if(tot == 0) then
			return tot
		else
			return (dbp['mailunread'] .. "/" .. tot)
		end
	else
		return tot
	end
end
local function iterateMail()
	for i = 1, GetInboxNumItems() do
		if(not select(9,GetInboxHeaderInfo(i))) then
			return 1
		end
	end
	return
end
function events:MAIL_SHOW(event)
	dbp['newmail'] = HasNewMail()
	if(MailFrame:IsVisible() and GetInboxNumItems() > 0) then
		dbp['newmail'] = iterateMail()
	end
	child:OnText(childName, child:colorize(mail(),dbp['newmail'] and "00ff00" or "ffffff"))
	if(event == "MAIL_SHOW") then
		scanned = true
	elseif(event == "UPDATE_PENDING_MAIL") then
		scanned = false
	end
end
events.MAIL_CLOSED = events.MAIL_SHOW
child['specs']  = {
	['name'] = childName,
	['sv'] = true,
	['cfg'] = true,
	['cfgReset'] = prepareDB,
	['ldb'] = child['ldb'],
	['defaults'] = {
		['profile'] = {
			[childName] = {}
		}
	}
}
function events:PLAYER_ENTERING_WORLD()
	if(not realm) then
		prepareDB()
	else
		child:UnregisterEvent('PLAYER_ENTERING_WORLD')
		child:RegisterEvent({'MAIL_INBOX_UPDATE', 'UPDATE_PENDING_MAIL'}, events.MAIL_SHOW)
		events.MAIL_SHOW()	
	end
end
child:NewAddOn(...)