local Messenger = require("Framework.Common.Messenger")
local EventNotify = CS.EventNotify
local EventManager = BaseClass("EventManager", Singleton)
local __init = function(self)
  self.messenger = Messenger.New()
end
local __delete = function(self)
  self.messenger = nil
end
local AddListener = function(self, eventId, handler)
  self.messenger:AddListener(eventId, handler)
end
local RemoveListener = function(self, eventId, handler)
  self.messenger:RemoveListener(eventId, handler)
end
local AddListenerWithSelf = function(self, eventId, handler, obj)
  self.messenger:AddListener(eventId, handler, obj)
end
local RemoveListener2 = function(self, eventId, handler, obj)
  self.messenger:RemoveListener(eventId, handler)
end
local Broadcast = function(self, eventId, userData)
  if eventId == nil then
    return
  end
  if userData == nil then
    EventNotify.Fire(eventId)
    return
  end
  local t = type(userData)
  if t == "number" then
    EventNotify.FireLong(eventId, userData)
  elseif t == "boolean" then
    EventNotify.FireBool(eventId, userData)
  elseif t == "string" then
    EventNotify.FireString(eventId, userData)
  elseif t == "table" and userData.ToBinary then
    EventNotify.FireSFSObject(eventId, userData:ToBinary())
  elseif t == "table" then
    EventNotify.FireLuaTable(eventId, userData)
  else
    Logger.LogError("broadcast type error ", eventId)
  end
end
local DispatchCSEvent = function(self, eventId, userData)
  self.messenger:Broadcast(eventId, userData)
end
local DispatchCSEventSFSObject = function(self, eventId, userData)
  local sfsObj = SFSObject.NewFromBinary(userData)
  self.messenger:Broadcast(eventId, sfsObj)
end
local DelayBroadcast = function(self, delayTime, eventId, userData)
  local delayBroadcast = self.delayBroadcast
  if delayBroadcast == nil then
    delayBroadcast = {}
  end
  local key = userData or "Null_Delay_Broadcast"
  local eventList = delayBroadcast[eventId] or {}
  if eventList[key] == nil then
    local theEventId = eventId
    local theUserData = userData
    eventList[key] = TimerManager:GetInstance():DelayInvoke(function()
      eventList[key] = nil
      EventManager:GetInstance():Broadcast(theEventId, theUserData)
    end, delayTime or 0.1)
    delayBroadcast[eventId] = eventList
    self.delayBroadcast = delayBroadcast
  end
end
EventManager.__init = __init
EventManager.__delete = __delete
EventManager.AddListener = AddListener
EventManager.RemoveListener = RemoveListener
EventManager.AddListenerWithSelf = AddListenerWithSelf
EventManager.RemoveListener2 = RemoveListener2
EventManager.Broadcast = Broadcast
EventManager.DispatchCSEvent = DispatchCSEvent
EventManager.DispatchCSEventSFSObject = DispatchCSEventSFSObject
EventManager.DelayBroadcast = DelayBroadcast
return EventManager
