----------------------------------------------------------------
-- 文件名: event.lua
-- 日期: 2013-12-02
-- 描述: 内置YY事件分发
-- 作者: 盒子哥
-- 
----------------------------------------------------------------

local MAJOR, MINOR = "LibEvent", 1
local LibEvent, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
LibEvent.embeds = {}
local CallbackHandler = LibStub:GetLibrary("CallbackHandler")

local CEGUI	= CEGUI
local pairs = pairs

if not LibEvent.events then
	LibEvent.events = CallbackHandler:New(LibEvent, 
		"RegisterEvent", "UnregisterEvent", "UnregisterAllEvents")
end

-- APIs and registry for IPC messages, using CallbackHandler lib
if not LibEvent.messages then
	LibEvent.messages = CallbackHandler:New(LibEvent, 
		"RegisterMessage", "UnregisterMessage", "UnregisterAllMessages"
	)
	LibEvent.SendMessage = LibEvent.messages.Fire
end

--- embedding and embed handling
local mixins = {
	"RegisterEvent", "UnregisterEvent",
	"RegisterMessage", "UnregisterMessage",
	"SendMessage",
	"UnregisterAllEvents", "UnregisterAllMessages",
}

function LibEvent:Embed(target)
	for k, v in pairs(mixins) do
		target[v] = self[v]
	end
	self.embeds[target] = true
	return target
end

local events = LibEvent.events
function _OnUserEvent(args)
	local msg_args = CEGUI.toWndUserMessageArgs(args)
	local event_id = msg_args.nMessageID
	local wParam = msg_args.nWParam
	local lParam = msg_args.nLParam		
	
	if (event_id == WM_MSG_PACKET or event_id == WM_DATA_PACKET) then
		local Packet = {}	
	
		Packet = PacketBase:CreateRecv( wParam, lParam )		
		local protocol = Packet:GetInteger( 4 )

		local event_handle = PROTOCOL_TO_NAME[protocol];
		if (type(event_handle) == "table") then
			events:Fire(event_handle[1], event_handle[2](Packet))
			--__LOG__(event_handle[1])
		elseif (type(event_handle) == "string") then
			events:Fire(event_handle, Packet)
			--__LOG__(event_handle)
		else
			__LOG__(("%s:_OnUserEvent(): 0x%X protocol_id: 0x%X - not find map value."):format(MAJOR, event_id, tonumber(protocol) or -1))
		end		
	else
		local event_handle = EVENT_TO_NAME[event_id]
		if (type(event_handle) == "table") then
			events:Fire(event_handle[1], event_handle[2](wParam, lParam))
			--__LOG__(event_handle[1])
		elseif (type(event_handle) == "string") then
			events:Fire(event_handle, wParam, lParam)
			--__LOG__(event_handle)
		else
			__LOG__(("%s:_OnUserEvent(): event_id: 0x%X- not find map value."):format(MAJOR, event_id))
		end		
	end
end

local root = CEGUI.System:getSingleton():getGUISheet();
root:subscribeEvent("WndUserMessage", _OnUserEvent)