local this = class("modulePetDuelMiniMap", G_UIModuleBase)
local iconMap = {
  playerPet = 0,
  enemyPet = 1,
  player = 2,
  enemy = 3,
  playerTower = 4,
  enemyTower = 5
}

function this.bind()
  return {
    markList = {
      moduleName = "pages/petDuel/cellMiniPos"
    },
    mapImg = "",
    panelActive = true
  }
end

function this.methods()
  return {}
end

function this:open()
  self.entityMarks = {}
  self.updateHandle = handler(self, self.update)
  C_UpdateSource.AddUpdateEventHandler(self.updateHandle, "movement.modulePetDuelMiniMap.update")
end

function this:initMap(duelId)
  local kiBoDuelTpl = L_GameTpl:getKiboDuelTpl()
  local tpl = kiBoDuelTpl:getTplById(duelId)
  local worldAreaId = kiBoDuelTpl:getWorldAreaId(tpl)
  self.bind.panelActive = not math.isEmpty(worldAreaId)
  if not self.bind.panelActive then
    return
  end
  local worldAreaTpl = L_GameTpl:getWorldAreaTpl()
  local areaTpl = worldAreaTpl:getTplById(worldAreaId)
  self.bind.mapImg = worldAreaTpl:getAreaMap(areaTpl)
  self.mapData = L_MapManager:createMapData(worldAreaId, true)
end

function this:close()
  C_UpdateSource.RemoveUpdateEventHandler(self.updateHandle)
end

function this:update()
  if not self.bind.panelActive then
    return
  end
  if not self.mapData then
    return
  end
  self:parseData()
  if #self.entityMarks == #self.bind.markList then
    for i = 1, #self.bind.markList do
      self.bind.markList:change(i, self.entityMarks[i])
    end
  else
    self.bind.markList:clear()
    self.bind.markList:insert_array(self.entityMarks)
  end
end

function this:parseData()
  self.entityMarks = {}
  local entities = C_KiBoDuelLuaWrapper.GetAllEntityData()
  for _, entity in pairs(entities) do
    self:dealIconId(entity)
  end
  if self.mapData then
    table.insert(self.entityMarks, {
      mapData = self.mapData,
      selectTabId = iconMap.player
    })
  end
end

function this:dealIconId(entity)
  if not self.mapData then
    return
  end
  if entity.campType == C_ECampType.Red then
    if entity.entityType == C_EEntityType.BaseTower then
      table.insert(self.entityMarks, {
        mapData = self.mapData,
        selectTabId = iconMap.enemyTower,
        entityTans = entity.entityTrans
      })
    end
    if entity.entityType == C_EEntityType.KiBo then
      table.insert(self.entityMarks, {
        mapData = self.mapData,
        selectTabId = iconMap.enemyPet,
        entityTans = entity.entityTrans
      })
    end
  end
  if entity.campType == C_ECampType.Blue then
    if entity.entityType == C_EEntityType.BaseTower then
      table.insert(self.entityMarks, {
        mapData = self.mapData,
        selectTabId = iconMap.playerTower,
        entityTans = entity.entityTrans
      })
    end
    if entity.entityType == C_EEntityType.KiBo then
      table.insert(self.entityMarks, {
        mapData = self.mapData,
        selectTabId = iconMap.playerPet,
        entityTans = entity.entityTrans
      })
    end
  end
end

return this
