local this = {}

function this:initServer()
  self:stopServer()
  self.foodStorageMax = L_GameConstTpl:getHomeFoodStorage()
  self.tik = 1
  self:startServer()
end

function this:startServer()
  if self.serverTimer then
    return
  end
  local frequency = 1
  local _run = function()
    self:refreshFoodStorage()
  end
  self:refreshFoodStorage()
  self.serverTimer = Timer.repeated(frequency, _run)
end

function this:stopServer()
  if not self.serverTimer then
    return
  end
  self.serverTimer:destroy()
  self.serverTimer = nil
end

function this:refreshFoodStorage()
  local now = L_TimeUtil.getServerTime()
  local lastTime = now - self.data.refreshTime
  local minuteNum = math.floor(lastTime / 60)
  for i = 1, minuteNum do
    local speed = 0
    local cost = L_HomeResidentStore:getFoodCostSum()
    if self.data.foodStorage < self.foodStorageMax then
      local proNum = self:getCanteenProductSum()
      self:stickCanteenTime()
      speed = speed + proNum
      if math.isEmpty(proNum) and (math.isEmpty(self.data.foodStorage) or math.isEmpty(cost)) then
        self:call(self.event.refreshFoodStorage)
        self:stopServer()
        return
      end
    end
    speed = speed - cost
    self.data.foodStorage = math.clamp(self.data.foodStorage + speed, 0, math.maxinteger)
    self.data.refreshTime = self.data.refreshTime + 60
  end
  self.tik = self.tik + 1
  if self.tik % 600 == 0 then
    self:req_CSProtoRefreshCanteen()
  end
  self:call(self.event.refreshFoodStorage)
end

return this
