local page = class("pageFps", G_UIPageBase)
page.sampleTime = 0.5
page.sampleTime10s = 10
page.sampleTime60s = 60
page.sampleTime10m = 600
page.sampleTimeTotal = 10
page.time = 0
page.time10s = 0
page.time60s = 0
page.time10m = 0
page.timeTotal = 0
page.frame = 0
page.frame10s = 0
page.frame60s = 0
page.frame10m = 0
page.frameTotal = 0

function page.bind()
  return {
    fps = "FPS: 0",
    fps10s = "(10s avg): 0",
    fps60s = "(60s avg): 0",
    fps10m = "(10m avg): 0",
    fpsTotal = "(Total avg): 0",
    fpsObj = true
  }
end

function page:preOpen()
  self.bind.fpsObj = Unity.Debug.isDebugBuild
  self.strTab = {
    1,
    "X",
    3,
    "_",
    5,
    " FPS:",
    7,
    " ",
    9,
    " ",
    11,
    " ",
    13,
    " ",
    15,
    " time:",
    17
  }
  C_UpdateSource.AddUpdateEventHandler(handler(self, self.updateFps), "pageFps(\229\191\189\231\149\165)")
end

function page:updateFps()
  if self.bind.fpsObj then
    local delta = Unity.Time.deltaTime
    page.frame = page.frame + 1
    page.time = page.time + delta
    page.frame10s = page.frame10s + 1
    page.time10s = page.time10s + delta
    page.frame60s = page.frame60s + 1
    page.time60s = page.time60s + delta
    page.frame10m = page.frame10m + 1
    page.time10m = page.time10m + delta
    page.frameTotal = page.frameTotal + 1
    page.timeTotal = page.timeTotal + delta
    if page.time >= page.sampleTime then
      local fpsCount = page.frame / page.time
      self.bind.fps = self:getString(fpsCount)
      page.frame = 0
      page.time = 0
    end
    if page.time10s >= page.sampleTime10s then
      local fps10sCount = page.frame10s / page.time10s
      self.bind.fps10s = string.format("(10s avg): %.1f", fps10sCount)
      page.frame10s = 0
      page.time10s = 0
    end
    if page.time60s >= page.sampleTime60s then
      local fps60sCount = page.frame60s / page.time60s
      self.bind.fps60s = string.format("(60s avg): %.1f", fps60sCount)
      page.frame60s = 0
      page.time60s = 0
    end
    if page.time10m >= page.sampleTime10m then
      local fps10mCount = page.frame10m / page.time10m
      self.bind.fps10m = string.format("(10m avg): %.1f", fps10mCount)
      page.frame10m = 0
      page.time10m = 0
    end
    local fpsTotalCount = page.frameTotal / math.max(page.timeTotal, 0.001)
    self.bind.fpsTotal = string.format("(Total avg): %.1f", fpsTotalCount)
  end
end

function page:getString(fpsCount)
  local ac = C_UniversalRenderPipeline.renderScale or "1"
  self.strTab[1] = C_Screen.width
  self.strTab[3] = C_Screen.height
  self.strTab[5] = ac
  self.strTab[7] = string.format("%.1f", fpsCount)
  self.strTab[9] = self.bind.fps10s
  self.strTab[11] = self.bind.fps60s
  self.strTab[13] = self.bind.fps10m
  self.strTab[15] = self.bind.fpsTotal
  self.strTab[17] = L_TimeUtil.getDisplayTime()
  return table.concat(self.strTab)
end

return page
