local addonName, addon = ...
local childName = addon['childName']
local child = addon[childName]
local events = child['events']
local db, crealm
local fmt = "|c0000ff00%i|r/|c0000ffff%i|r|c00ff0000%s|r"
local roster,friendroster,bnetroster = {}, {}, {}
local GuildRoster = GuildRoster
if(C_GuildInfo) then
	if(C_GuildInfo.GuildRoster) then
		GuildRoster = C_GuildInfo.GuildRoster
	end
end
local updateDelay = 15
local function prepareDB()
	db = addon['db']['profile'][childName]
	child['db'] = db
	addon['callbacks']:Fire(format("Init%s", childName))
end
local function count(v)
	local c = 0
	for _ in pairs(v) do
		c = c + 1
	end
	return c
end
local function checkRoster(self, dummy, event, ...)
	local newroster = {}
	local rostername, online, _
	local dontShow = false

	if(event == "GUILD_ROSTER_UPDATE") then
		for i=1,GetNumGuildMembers() do
			rostername, _, _, _, _, _, _, _, online = GetGuildRosterInfo(i)
			if(online and rostername) then
				newroster[rostername]=true
			end
		end
		roster = newroster
	elseif(event == "FRIENDLIST_UPDATE") then
		for i = 1, C_FriendList.GetNumFriends() do
			local res = C_FriendList.GetFriendInfoByIndex(i)
			if(res) then
				if(res['connected'] and res['name']) then
					newroster[res['name']] = true
				end
			end
		end
		friendroster = newroster
	elseif(event == "BN_FRIEND_INFO_CHANGED") then
		local _, numOnline = BNGetNumFriends()
		local presenceID, isFriend,client,accid
		for i = 1, numOnline do
			local res = C_BattleNet.GetFriendAccountInfo(i)
			if(res) then
				local aci = res['gameAccountInfo']
				dontShow = false
				if(aci) then
					if(aci['clientProgram'] == BNET_CLIENT_WOW) then
						if(aci['realmName'] == crealm and friendroster[aci['characterName']]) then
							dontShow = true
						end
					end
					if(aci['isOnline'] and aci['characterName'] and not dontShow) then
						newroster[aci['characterName']] = true
					end
				end
			end
		end
		bnetroster = newroster
	end
	local afkmsg = ""
	if(UnitIsAFK("player")) then
		afkmsg = " AFK"
	elseif(UnitIsDND("player")) then
		afkmsg = " DND"
	end
	child:OnText(childName, format(fmt, count(roster),count(friendroster)+count(bnetroster),afkmsg))
end

local function OnUpdate()
	GuildRoster()
	checkRoster(nil, nil, "FRIENDLIST_UPDATE")
	checkRoster(nil, nil, "BN_FRIEND_INFO_CHANGED")
	C_Timer.After(updateDelay, OnUpdate)
end
child['specs']  = {
	['name'] = childName,
	['sv'] = true,
	['cfg'] = true,
	['cfgReset'] = prepareDB,
	['ldb'] = child['ldb'],
	['defaults'] = {
		['profile'] = {
			[childName] = {}
		}
	}
}
function events:PLAYER_ENTERING_WORLD(event)
	crealm = GetRealmName()
	if(crealm) then
		child:UnregisterEvent('PLAYER_ENTERING_WORLD')
		child:RegisterEvent({"GUILD_ROSTER_UPDATE","FRIENDLIST_UPDATE","CHAT_MSG_CHANNEL_JOIN","CHAT_MSG_CHANNEL_LEAVE","PLAYER_FLAGS_CHANGED","UNIT_FLAGS","BN_FRIEND_INFO_CHANGED"}, checkRoster)
		OnUpdate()
	end
end
child:NewAddOn(...)