local Time = Time
local FixPointGenZombieTask = BaseClass("FixPointGenZombieTask")

function FixPointGenZombieTask:__init(battleMgr, limit, interval, pointId, sceneMeta, triggerId)
  self.battleMgr = battleMgr
  self.limit = limit
  self.interval = interval / 1000
  self.pointId = pointId
  self.lastTickTime = 0
  self.genNum = 0
  self.sceneMeta = sceneMeta
  self.triggerId = triggerId
end

function FixPointGenZombieTask:Update()
  local now = Time.time
  if now - self.lastTickTime > self.interval then
    self.lastTickTime = now
    self:DoLogic()
  end
end

function FixPointGenZombieTask:DoLogic()
  if self.genNum > self.limit then
    self.battleMgr:RemoveGenZombieTask(self)
    return
  end
  if self.battleMgr.squad == nil then
    return
  end
  local genPos = self.battleMgr.zombiePointMgr.pointMap[self.sceneMeta.id][self.pointId].pos
  local triggerMonsterGroup = self.sceneMeta.triggerMonsterGroup
  local p = self.sceneMeta.triggerMonsterProbability or 0
  if triggerMonsterGroup == nil then
    triggerMonsterGroup = {}
    p = 0
    local group = string.split(self.sceneMeta.trigger_monster_group, ",")
    for _, item in ipairs(group) do
      local innerItem = string.split(item, "|")
      p = p + tonumber(innerItem[2])
      triggerMonsterGroup[#triggerMonsterGroup + 1] = {
        id = tonumber(innerItem[1]),
        probability = p
      }
    end
    self.sceneMeta.triggerMonsterGroup = triggerMonsterGroup
    self.sceneMeta.triggerMonsterProbability = p
  end
  local random = math.random(0, p)
  local targetId = 0
  for _, item in ipairs(triggerMonsterGroup) do
    targetId = item.id
    if random <= item.probability then
      break
    end
  end
  self.battleMgr:CreateMonster(targetId, genPos, nil, self.triggerId)
  self.genNum = self.genNum + 1
end

return FixPointGenZombieTask
