local this = class("moduleDuelTarget", G_UIModuleBase)
local kiBoDuelTpl = L_GameTpl:getKiboDuelTpl()
local kiBoDuelTaskTpl = L_GameTpl:getKiboDuelTaskTpl()

function this.bind()
  return {
    targetList = {
      moduleName = "pages/petDuel/cellPetDuelTarget"
    },
    contentActive = false
  }
end

function this.methods()
  return {}
end

function this:open()
  self:resetData()
  self:initTargetData()
  L_KiBoDuelManager:addListener(L_KiBoDuelManager.event.restartKiBoDuel, self.restartKiBoDuel, self)
  L_KiBoDuelManager:addListener(L_KiBoDuelManager.event.taskCompeleted, self.refreshData, self)
end

function this:close()
  L_KiBoDuelManager:removeListener(L_KiBoDuelManager.event.restartKiBoDuel, self.restartKiBoDuel, self)
  L_KiBoDuelManager:removeListener(L_KiBoDuelManager.event.taskCompeleted, self.refreshData, self)
end

function this:restartKiBoDuel()
  self:resetData()
  self:initTargetData()
end

function this:initTargetData()
  self.duelId = L_PetDuelStore:getCurChallengeLevelId()
  self.targetData = {}
  local tpl = kiBoDuelTpl:getTplById(self.duelId)
  local tasks = kiBoDuelTpl:getTask(tpl)
  for _, id in ipairs(tasks) do
    table.insert(self.targetData, {id = id, value = 0})
  end
  self.bind.contentActive = #self.targetData > 0
  if not self.bind.contentActive then
    return
  end
  self:refreshTargetList()
end

function this:refreshTargetList()
  if #self.targetData > 0 then
    local data
    for _, v in ipairs(self.targetData) do
      local tpl = kiBoDuelTaskTpl:getTplById(v.id)
      if v.value < kiBoDuelTaskTpl:getCompletionTimes(tpl) then
        data = v
        break
      end
    end
    data = data or self.targetData[#self.targetData]
    if 0 < #self.bind.targetList then
      self.bind.targetList:change(1, data)
    else
      self.bind.targetList:insert_array({data})
    end
  end
end

function this:refreshData(data)
  local isFound = false
  for _, v in ipairs(self.targetData) do
    if v.id == data.id then
      v.value = v.value + 1
      isFound = true
    end
  end
  self:refreshTargetList()
end

function this:resetData()
  self.bind.targetList:clear()
  self.targetData = {}
end

return this
