-------------------------------------
-- 处理C++的调用请求
-------------------------------------

local common = LibStub("LibAddon"):GetAddon("common", "LibEvent", "LibTimer")
local protocol_event = common:NewModule("protocol_event", "LibEvent")
local loc_db_is_first_show = true
local loc_db_is_limit_move = true;

local module = protocol_event

function cplusplus_getret()
	return common.global["g_result_info"]
end

function module:OnInitialize()
	self:debug("common:OnInitialize()")	
	self:RegistrEvents()	
	self:registerProtocolEvents()	
end

function module:RegistrEvents()
	local wnd_mgr = CEGUI.WindowManager:getSingleton()
	local obj_root_wnd = wnd_mgr:getWindow("root")
	obj_root_wnd:subscribeEvent("GlobalKeyDown", self.on_global_keydown, self)
end

function module:registerProtocolEvents()	
	self:RegisterEvent("WM_SHOWINTERNALYY", "on_show_smartYY")
	self:RegisterEvent("WM_MOVEINTERNALYY", "on_move_smartYY")
	self:RegisterEvent("WM_RENDER_FINISH", "on_render_finish")
	self:RegisterEvent("WM_PRODUCT_SHOW_MOUSE", "on_show_mouse")
	self:RegisterEvent("WM_RESET_SMARTYY", "on_reset_smartyy")
	self:RegisterEvent("WM_PRODUCT_START_LOGIN", "on_start_login")
	self:RegisterEvent("WM_SET_MOVE_MOD", "on_set_move_mod")
	
end

function module:on_global_keydown(args)
	local key = CEGUI.toKeyEventArgs(args)
	--self:debug("on_global_keydown, scancode:", key.scancode, "window name:", key.window:getName())

	--local mainbar_name = "MainMsgHot_Parent"
	local smartYY_window_name = {
		["LoginWnd"] = true,

		["RegisterWnd"] = true,
		["RegisterSuccessWnd"] = true,
		["RegisterWarningWnd"] = true,

		["UserProtocolWnd"] = true,
		["GuestWnd"] = true,

		["MainWnd"] = true,
		["ChannelMsg"] = true,

		["OptionWnd"] = true,
		["TestVoiceWnd"] = true,

		["GameAccountBindWnd"] = true,
		["GameAccountBindSuccessWnd"] = true,
		["GameAccountBindFailedWnd"] = true,

		["UnionBindWnd"] = true,
		["RoomBindListWnd"] = true,
		["UnionCallWarnWnd"] = true,
		["RoomBindSuccessWnd"] = true,
		["RoomBindFailedWnd"] = true,
		["RoomBindTypeWnd"] = true,
		["CreateChannelWnd"] = true,

		["PopupMenu"] = true,
		["CommonOneBtnwnd"] = true,
		["CommonYesNoWnd"] = true,
		["SendInviteWnd"] = true,
		["RecvInviteWnd"] = true,
		["InviteMainWnd"] = true,
		["invite_warming_wnd"] = true,
		
	}

	-- 按esc关闭当前焦点窗口
	if key.scancode == 0x01 then
		local count = #smartYY_window_name

		local cur_wnd = nil
		local name = nil
		local parent_window = key.window
		--self:debug("parent_window:", tostring(parent_window))

		while parent_window ~= nil do
			cur_wnd = parent_window
			name = cur_wnd:getName()
			--self:debug("current window name:", name)

			if smartYY_window_name[name] == true then
					
				if cur_wnd:testClassName("FrameWindow") then
					key.window = cur_wnd
					cur_wnd:fireEvent("CloseClicked", CEGUI.toEventArgs(key), "FrameWindow")
					--self:debug("close current focus frame window!")
				elseif cur_wnd:testClassName("PopupMenu") then
					cur_wnd:hide()
					--self:debug("close current focus popup menu!")
				end
				--cur_wnd:moveToBack()

				local root = cur_wnd:getRootWindow()
				--self:debug("root name:", root:getName())
				local n = root:getChildCount()
				--self:debug("root has child count:", n)

				local local_cur_wnd = nil
				local last_render_wnd = nil
				while n >= 0 do
					n = n - 1
					local_cur_wnd = root:getRenderWindowAtIdx(n)
					name = local_cur_wnd:getName()
					--self:debug("local_cur_window name:", name)
					if smartYY_window_name[name] == true then
						last_render_wnd = local_cur_wnd
					else
						last_render_wnd = self:getLastRenderWindow(local_cur_wnd, local_cur_wnd:getChildCount() - 1)
					end
					if last_render_wnd ~= nil and last_render_wnd:isVisible() then
						--self:debug("find top render window, name:", last_render_wnd:getName())
						break
					end
				end

				if last_render_wnd then
					last_render_wnd:activate()
					last_render_wnd:moveToFront()
				end

				return
			end

			parent_window = cur_wnd:getParent()
		end

		--self:debug("can't find focus window.")
		key.handled = -1
		
	-- 处理数-1,让系统正常处理
	else
		key.handled = -1
	end
end

function module:getLastRenderWindow(root, index)
	local last_render_wnd = nil
	while index >= 0 do
		local child_wnd = root:getRenderWindowAtIdx(index)
		--self:debug("child index:", index, " name:", child_wnd:getName(),
			--" activate:", tostring(child_wnd:isActive()),
			--" visible:", tostring(child_wnd:isVisible()))

		if child_wnd:isVisible() then
			last_render_wnd = child_wnd
			--self:debug("child name:", child_wnd:getName())
		end

		index = index - 1
	end

	if last_render_wnd ~= nil then
		--self:debug("return last render window name:", last_render_wnd:getName())
	end
	return last_render_wnd
end

function module:on_show_smartYY(event, bSet)
	self:print(("on_show_smartYY bSet:%s, g_miniyy_connect:%s, g_yy_connect:%s"):
		format(tostring(bSet), tostring(common.global["g_miniyy_connect"]), tostring(common.global["g_yy_connect"])))

--[[	-- miniYY是否成功连接
	if common.global["g_miniyy_connect"] == false then
		common.global["g_result_info"] = 0
		return
	end
--]]

	-- 强制显示
	if bSet == true then
		if loc_db_is_first_show then
			loc_db_is_first_show = false;
			common.hiido:Count("smartyy_show", 1);
		end

		self:SendMessage("COMMON_NOTIFY_SHOW_SMARTYY");
		-- common.interface.mainbar:showMainWnd()
	-- 强制隐藏
	elseif bSet == false then
		self:SendMessage("COMMON_NOTIFY_HIDE_SMARTYY");
		-- common.interface.logon:hideMainWnd()
		-- common.interface.register:hideMainWnd()
		-- common.interface.mainbar:hideMainWnd()
		-- common.interface.mainwnd:hide()
		-- common.interface.setting:hideMainWnd()
		-- common.interface.testvoice:hideMainWnd()
	end

	common.global["g_result_info"] = 1
end

function module:on_set_move_mod(event, flg)
	self:print("common:on_set_move_mod flg:" .. tostring(flg))

	loc_db_is_limit_move = flg;
end

function module:on_move_smartYY(event, pos_x, pos_y)
	self:print("common:on_move_smartYY pos_x:" .. pos_x .. ", pos_y:" .. pos_y)

	if loc_db_is_limit_move == true then
		local posX = common.interface.config:get("nMainBarposX")
		local posY = common.interface.config:get("nMainBarposY")
		local scaleX = common.interface.config:get("fMainBarscaleX")
		local scaleY = common.interface.config:get("fMainBarscaleY")

		 --这里会导致 只有第一次调用接口才有用的 BUG
		if posX ~= common.const["g_defaultMainbarposX"] or posY ~= common.const["g_defaultMainbarposY"] or
			scaleX ~= common.const["g_defaultMainbarscaleX"] or scaleY ~= common.const["g_defaultMainbarscaleY"] then
			return
		end

		common.global["g_first_set_move"] = true
	end
	-- 设定位置生效
	common.interface.mainbar:setPosition(pos_x, pos_y)
end

function module:on_render_finish(event, ...)
	CUIControl:getSingleton():NotifyAfterDrawingSignal()
end

function module:on_show_mouse(event, bshow)
	if bshow == false then
		CEGUI.MouseCursor:getSingleton():hide();	-- 隐藏鼠标
	else
		CEGUI.MouseCursor:getSingleton():show();	-- 显示鼠标
	end
end

function module:on_reset_smartyy(event, ...)
	--关闭所有窗口，只显示工具条
	common.interface.channelbind:hideAllWindows()

	self:SendMessage("COMMON_NOTIFY_RESET_SMARTYY");

	-- common.interface.logon:hideMainWnd()
	-- common.interface.mainwnd:hide()
	-- common.interface.setting:hideMainWnd()
	-- common.interface.register:hideMainWnd()
	-- common.interface.testvoice:hideMainWnd()

	-- 刷新绑定频道列表
	CUIControl:getSingleton():refresh_game_bind_state();
	--
end

function module:on_start_login(event, username, password, visible)
	self:debug(("on_start_login username:%s, password:%s, visible:%s"):format(username,password,tostring(visible)))
	common.interface.logon:startLogin(username, password, visible)
end
