local this = class("homeResidentManager", G_EventManagerBase)
local residentDataPath = L_R.world.home .. "entity.homeResidentEntityData"
local residentEntityPath = L_R.world.home .. "entity.homeResidentEntity"
local homeTileTpl = L_GameTpl:getHomeTileTpl()

function this:ctor()
  this.super.ctor(self)
  self.residentEntityMap = {}
end

function this:enterHome()
  if self._residentRoot == nil then
    self._residentRoot = Unity.GameObject("[Home-Resident]").transform
  end
  
  function self._refreshFunc()
    self:updateResident()
  end
  
  L_HomeResidentStore:listenCallFunc(L_HomeResidentStore.event.residentDataUpdate, self._refreshFunc)
  self:updateResident()
end

function this:updateResident()
  do return end
  local residents = L_HomeResidentStore:getAllResident()
  for id, entity in pairs(self.residentEntityMap) do
    if entity then
      local resident = residents[id]
      local entityData = entity:getEntityData()
      if not resident or resident.type ~= entityData:getCurrType() then
        self:destroyResident(id)
      end
    end
  end
  for id, resident in pairs(residents) do
    if self.residentEntityMap[id] == nil then
      self:createResident(id)
    end
    if self.residentEntityMap[id] then
      self.residentEntityMap[id]:checkBuilding()
    end
  end
end

function this:createResident(id)
  local entityData = require(residentDataPath).new(id)
  local blockId = 1
  local tpl = homeTileTpl:getTplById(blockId)
  local pos = homeTileTpl:getOffsetPos(tpl)
  pos.x = pos.x + 20 + math.random(1, 300) / 100
  pos.z = pos.z + 30 + math.random(1, 300) / 100
  self.residentEntityMap[id] = false
end

function this:destroyResident(id)
  local currEntity = self.residentEntityMap[id]
  if not currEntity then
    self.residentEntityMap[id] = nil
    return
  end
  local cEntityId = currEntity:getCsEntityId()
  currEntity:onDestroy()
  L_CsEntityManager:removeEntityWithEntityId(cEntityId)
  self.residentEntityMap[id] = nil
end

function this:exitHome()
  for id, _ in pairs(self.residentEntityMap) do
    self:destroyResident(id)
  end
  L_HomeResidentStore:unListenCallFunc(L_HomeResidentStore.event.residentDataUpdate, self._refreshFunc)
end

return this
