package ocelot.desktop.util

class FPSCalculator {
  private var prevTime = System.currentTimeMillis()
  private var prevFrameTime = System.currentTimeMillis()
  private var numFrames = 0

  private var _fps: Float = 0f

  def fps: Float = _fps

  private var _skipSecond = false

  /**
    * Current second will not count towards the overall statistics.
    * (In case the measurements were corrupted or distorted somehow.)
    */
  def skipSecond(): Unit = _skipSecond = true

  var dt: Float = 0

  def tick(): Unit = {
    val currentTime = System.currentTimeMillis()

    dt = (currentTime - prevFrameTime) / 1000f
    numFrames += 1

    if (currentTime - prevTime > 1000) {
      val delta = currentTime - prevTime
      prevTime = currentTime
      if (!_skipSecond) {
        _fps = numFrames.toFloat / delta * 1000.0f
      } else {
        _skipSecond = false
      }
      numFrames = 0
    }

    prevFrameTime = currentTime
  }
}
