/*
  timer.js
  fffadedev
  08/24/25

  Countdown a timer for a fixed number of seconds
 */

class Timer
{
  constructor(defaultTime) {
    this.resetTime = defaultTime;
    this.interval = null;
  }

  reset() {
    this.secondsLeft = this.resetTime;
    this.isRunning = false;
    window.clearInterval(this.interval);
    this.interval = null;
  }

  pause() {
    this.isRunning = false;
  }

  start() {
    this.isRunning = true;
    this.interval = window.setInterval((() => {
      if(this.isRunning) {
        this.secondsLeft--;
        // Custom event that triggers when seconds reach zero
        if(this.secondsLeft <= 0) {
          this.isRunning = false;
          if(this.onEnd !== null) {
            this.onEnd();
          }
        }
      }
      // Custom event that triggers on each second change
      if(this.onChange !== null)
        this.onChange(this.secondsLeft);
    }).bind(this), 1000);
  }
}
