
--===================================================
--									
--										GHI Ping
--									ghi_ping.lua
--
--						Manual ping to other clients
--	
-- 						(c)2011 The Gryphonheart Team
--								All rights reservated
--===================================================

local class;
function GHI_Ping()
	if class then 
		return class;
	end
	class = GHClass("GHI_Ping");
	
	
	local PING = "Ping";
	local PING_REPLY = "PingReply";
	
	local pingedPlayer = {};
	local comm = GHI_Comm();
	local pingCallbackFuncs = {};
	
	local CapitalizeFirstLetterOfString = function(str)
		return strupper(strsub(str,0,1))..strlower(strsub(str,2));
	end
	
	local RecievePing = function(sender,version,...)
		if pingedPlayer[sender] then
			GHI_Message("Ping reply from "..(sender or "nil"));
			GHI_Message("Version "..(version or "nil"));
			pingedPlayer[sender] = nil;	
		end
		
		for _,func in pairs(pingCallbackFuncs) do
			func(sender,version);		
		end
	end
	
	local AnswerPing = function(sender,...)
		local playerGhiVersion = GetAddOnMetadata("GHI", "Version");
		comm.Send("ALERT",sender,PING_REPLY,playerGhiVersion);
	end
	
	class.SendPing = function(player,silent)
		if not(strlen(player)>0) then
			return;		
		end
		
		player = CapitalizeFirstLetterOfString(player);
		comm.Send("ALERT",player,PING);
		
		if not(silent) then
			pingedPlayer[player]=true;
		end
	end
	
	class.RegisterRecievePingFunc = function(func)
		assert(type(func)=="function");
		table.insert(pingCallbackFuncs,func);
	end
	
	comm.AddRecieveFunc(PING,AnswerPing)
	comm.AddRecieveFunc(PING_REPLY,RecievePing);
	return class;
end


