
--===================================================
--									
--								GHI Item Data Transfer
--							ghi_itemDataTransfer.lua
--
--	Syncronisation and transfering of item data betweet clients
--	
-- 						(c)2011 The Gryphonheart Team
--								All rights reservated
--===================================================

local class;
function GHI_ItemDataTransfer()
	if class then
		return class;	
	end
	class = GHClass("GHI_ItemDataTransfer");
	
	local comm = GHI_Comm();
	
		
	 
	
	local recieveItemDataRequest = function(player,ID,...)
		if type(GHI_ItemData[ID]) == "table" then
			local data = {};
			for index1,value1 in pairs(GHI_ItemData[ID]) do
				if not(index1 == "rightClick") then
					data[index1] = value1;
				end	
			end
			comm.Send(nil,player,"ItemData",ID,data)
		end
	end
	
	local recieveItemVersion = function(player,ID,version,...)
		local ownVersion = GHI_GetVersions(ID);
		if ownVersion < version then
			comm.Send("ALERT",player,"ItemDataRequest",ID);
		elseif ownVersion > version then
			recieveItemDataRequest(player,ID);
		end
	end
	
	local recieveItemData = function(player,ID,data,...)
		GHI_ItemData[ID] = GHI_ItemData[ID] or {};
		
		for index1,value1 in pairs(data) do
			if not(index1 == "rightClick") then
				GHI_ItemData[ID][index1] = value1;
			end
		end	
	end
	
	class.SyncItemLinkData = function(player,ID) 
		local version = GHI_GetVersions(ID);
		comm.Send("ALERT",player,"ItemVersion",ID,version);
	end
		
	class.SyncItemActionData = function(player,ID) 
		class.SyncItemLinkData(player,ID);
		local _,version = GHI_GetVersions(ID);
		comm.Send("ALERT",player,"ItemActionVersion",ID,version);
	end
	
	local recieveItemActionVersion = function(player,ID,version,...) 
		local _,ownVersion = GHI_GetVersions(ID);
		if ownVersion > version then
			if type(GHI_ItemData[ID]) == "table" then			
				comm.Send("BULK",player,"ItemActionData",ID,GHI_ItemData[ID].rightClick);
				comm.Send("ALERT",player,"ExpectItemActionData",ID,comm.GetQueueSize());
			end
		elseif ownVersion < version then
			class.SyncItemActionData(player,ID);
		end
	end
	
	local recieveItemActionData = function(player,ID,data,...)
		GHI_ItemData[ID] = GHI_ItemData[ID] or {};
		GHI_ItemData[ID].rightClick = data;
		GHI_AwaitingRCData[ID] = false;	
	end
	
	local recieveExpectItemActionData = function(player,ID,queueSize,...)
		GHI_AwaitingRCData[ID] = true;
		if queueSize and queueSize > 5000 then
			GHI_AwaitingRCDataTime[ID] = (queueSize/250)+time();
		else
			GHI_AwaitingRCDataTime[ID] = time();
		end
	end
	
	
	
	comm.AddRecieveFunc("ItemVersion",recieveItemVersion);
	comm.AddRecieveFunc("ItemDataRequest",recieveItemDataRequest);
	comm.AddRecieveFunc("ItemData",recieveItemData);
	
	comm.AddRecieveFunc("ItemActionVersion",recieveItemActionVersion);
	comm.AddRecieveFunc("ItemActionData",recieveItemActionData);
	comm.AddRecieveFunc("ExpectItemActionData",recieveExpectItemActionData);
	
	
	return class;
end

