-- TODO JJJ 实现消息队列
local common = LibStub("LibAddon"):GetAddon("common")
local ticket = common:NewModule("ticket", "LibEvent")

local default_db = {
	_queue = {},
}

function ticket:OnInitialize()
	self:debug("OnInitialize")
	self.db = default_db
	self:RegisterProtocolEvents()
end

function ticket:RegisterProtocolEvents()
	self:debug("RegisterProtocolEvents")
	self:RegisterEvent("YYT_TO_PIP_GETTICKTRESULT", "on_get_ticket")
end

function ticket:requestTicket(obj, callback, service_id)
	self:debug("requestTicket")

	if obj == nil or callback == nil then
		self:error("obj or callback is nil")
		return
	else
		local tbl = {}
		tbl.object 	 = obj
		tbl.callback = callback
		table.insert(self.db._queue,tbl)
	end

	if service_id == nil then
		service_id = 50010
	end
	local bRet = ClientService:getSingleton():GetTicket(service_id)
	if not bRet then
		self:error("unable to get ticket because of not login")
	end
	return bRet
end

function ticket:on_get_ticket(event, service_id, ticket)
	self:debug("on_get_ticket")
	if ( #self.db._queue > 0 ) then
		local obj,callback = self.db._queue[1].object,self.db._queue[1].callback
		if (obj ~= nil) and (callback ~= nil) then
			obj[callback](obj, ticket, service_id)
		end
		table.remove(self.db._queue,1)
	end
end