local this = class("operatorSendSystem", L_EcsConst.system)

function this:ctor(parent)
  this.super.ctor(self, parent)
  self.parent = parent
end

function this:onRemove()
  self:shutdownSyncPosition()
end

function this:onDestroy()
  self:shutdownSyncPosition()
end

function this:onSetMainHero(main, sou)
  if main then
    self:shutdownSyncPosition()
    self:syncPosition()
  else
    self:shutdownSyncPosition()
  end
end

function this:onSetMainGm(main, sou)
  self:shutdownSyncPosition()
end

function this:syncPosition(bevType, scale)
  self:checkPosition(bevType)
  if self.syncTimer == nil then
    self.syncTimer = Timer.repeated(scale or 0.3, self.checkPosition, self)
  end
end

function this:shutdownSyncPosition()
  if self.syncTimer then
    Timer.remove(self.syncTimer)
    self.syncTimer = nil
  end
end

function this:checkPosition(bevType)
  local curModule = L_WorldManager:getCurModule()
  local controlEntity = self.parent:getMainControlEntity()
  if controlEntity and controlEntity:isValid() then
    local curPos = controlEntity:getReltaivePositionByRootNode()
    if bevType == L_Const.serverMoveType.transfer then
      return
    end
    if self.mainPos == nil or L_Vector3.sqrDistance(self.mainPos, curPos) >= 1 then
      local curRot = controlEntity:getRotation()
      local data = {
        pos = {
          x = curPos.x,
          y = curPos.y,
          z = curPos.z
        },
        angle = curRot.y
      }
      if bevType then
        data.move_status = bevType
      else
      end
      if curModule == L_Const.worldModule.dungeon or curModule == L_Const.worldModule.multiDungeon then
        self.mainPos = curPos
      else
        L_AreaStore:refreshArea(curPos)
        local areaId = L_AreaStore:getAreaId()
        data.area_id = areaId
        if not math.isEmpty(areaId) then
          self.mainPos = curPos
        else
          self.mainPos = nil
        end
      end
      local _x = curPos.x * 100
      local _y = curPos.y * 100
      local _z = curPos.z * 100
      local _angel = curRot.y * 100
      C_EntityManager.HeroMoveCommand(_x, _y, _z, _angel, L_AreaStore:getAreaId(), bevType)
    end
  end
end

return this
