local Time = Time
local RandomGenZombieTask = BaseClass("RandomGenZombieTask")

function RandomGenZombieTask:__init(battleMgr, limit, interval, r1, r2, sceneMeta, groupType, triggerId)
  self.battleMgr = battleMgr
  self.limit = limit
  self.interval = interval / 1000
  self.r1 = r1
  self.r2 = r2
  self.lastTickTime = 0
  self.genNum = 0
  self.sceneMeta = sceneMeta
  self.groupType = groupType
  self.triggerId = triggerId
end

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

local _AutoMonsterGroupKeyMap = {
  default = "autoMonsterGroup",
  start = "startMonsterGroup",
  final = "finalMonsterGroup"
}
local _AutoMonsterGroupMetaFieldMap = {
  default = "auto_monster_group",
  start = "start_monster_group",
  final = "final_monster_group"
}
local _ParseMonsterGroup = function(self, groupType)
  local masterGroup = {}
  local p = 0
  local metaField = _AutoMonsterGroupMetaFieldMap[groupType]
  local group = string.split(self.sceneMeta[metaField], ",")
  for _, item in ipairs(group) do
    local innerItem = string.split(item, "|")
    p = p + tonumber(innerItem[2])
    masterGroup[#masterGroup + 1] = {
      id = tonumber(innerItem[1]),
      probability = p
    }
  end
  local groupKey = _AutoMonsterGroupKeyMap[groupType]
  self.sceneMeta[groupKey] = masterGroup
  self.sceneMeta[groupKey .. "Probability"] = p
end

function RandomGenZombieTask:DoLogic()
  if self.genNum >= self.limit then
    self.battleMgr:RemoveGenZombieTask(self)
    return
  end
  if self.battleMgr.squad == nil then
    return
  end
  local playerPos = self.battleMgr.squad:GetPosition()
  local dir = Vector3.Normalize(Vector3.New(math.random(-10000, 10000), 0, math.random(0, 20000)))
  local len = math.random(self.r2, self.r1)
  local genPos = playerPos + Vector3.New(0, 0, 10) + dir * len
  local groupKey = _AutoMonsterGroupKeyMap[self.groupType]
  if self.sceneMeta[groupKey] == nil then
    _ParseMonsterGroup(self, self.groupType)
  end
  local autoMasterGroup = self.sceneMeta[groupKey] or {}
  local p = self.sceneMeta[groupKey .. "Probability"] or 0
  local random = math.random(0, p)
  local targetId = 0
  for _, item in ipairs(autoMasterGroup) 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 RandomGenZombieTask
