local this = class("formationManager", G_EventManagerBase)
table.merge(this, require("ui.manager.formation.formationManager_scene"))
table.merge(this, require("ui.manager.formation.formationManager_net"))
this.event = {
  formationNoEnergy = "formationNoEnergy"
}

function this:ctor()
  this.super.ctor(self)
end

function this:showFormationTip(tipType)
  L_FlyMsgManager:showNormalMsgByKey(L_FormationConst.FormationTipDesc[tipType])
end

function this:getCurFormationType()
  local battleTypeModule = L_BattleStore:getCreateBattleType()
  if battleTypeModule == L_Const.createBattleType.tower then
    return L_FormationConst.FormationType.tower
  end
  local fType = L_FormationConst.FormationType.world
  return fType
end

function this:getNextAliveHeroIndex(id)
  local aliveHeroIdDic = {}
  if L_WorldManager:getCurModule() ~= L_Const.worldModule.bigBattleWorld then
    local type = L_FormationManager:getCurFormationType()
    local validHeroes = L_FormationStore:getFormationPosData(type)
    local isAllDead = true
    for i = 1, #validHeroes do
      local heroId = validHeroes[i]
      if heroId ~= 0 then
        local entity = L_PlayerManager:getPlayerUnit():getHero(heroId)
        if entity and not C_EntityManager.IsEntityDead(entity:getCsEntityId()) and 0 < C_MyFloatUtility.GetFloat(entity:getCsEntity().data.aliveProperty.hp) then
          isAllDead = false
        end
      end
    end
    if isAllDead then
      return nil
    end
    local startIndex = 1
    for i, v in ipairs(validHeroes) do
      if v == id then
        startIndex = i + 1
        break
      end
    end
    for i = startIndex, #validHeroes do
      local heroId = validHeroes[i]
      if heroId ~= 0 then
        local entity = L_PlayerManager:getPlayerUnit():getHero(heroId)
        if entity and not C_EntityManager.IsEntityDead(entity:getCsEntityId()) and 0 < C_MyFloatUtility.GetFloat(entity:getCsEntity().data.aliveProperty.hp) then
          return i
        end
      end
    end
    for i = 1, startIndex - 1 do
      local heroId = validHeroes[i]
      if heroId ~= 0 then
        local entity = L_PlayerManager:getPlayerUnit():getHero(heroId)
        if entity and not C_EntityManager.IsEntityDead(entity:getCsEntityId()) and 0 < C_MyFloatUtility.GetFloat(entity:getCsEntity().data.aliveProperty.hp) then
          return i
        end
      end
    end
    return nil
  else
    local heroDic = L_PlayerManager:getPlayerUnit():getAllHero()
    for i, v in pairs(heroDic) do
      if not C_EntityManager.IsEntityDead(v:getCsEntityId()) and 0 < C_MyFloatUtility.GetFloat(v:getCsEntity().data.aliveProperty.hp) then
        aliveHeroIdDic[i] = v
      end
    end
    local hero
    for i, v in pairs(aliveHeroIdDic) do
      if i ~= id then
        hero = i
        break
      end
    end
    return hero
  end
end

function this:switchMyPlayerMainControl(index, force)
  AzurWorld.playerMgr.myPlayerUnitAdapter:SwitchFormationMainControlIndex(index, nil, force == true)
end

return this
