import { EventEmitter } from 'pixi.js'

export class Timer extends EventEmitter {
  private intervalHandle?: any
  private countdown: number = 0

  constructor(private seconds: number) {
    super()
    this.countdown = seconds
  }

  start() {
    clearInterval(this.intervalHandle)
    this.intervalHandle = setInterval(() => {
      this.countdown--
      if (this.countdown === 0) {
        clearInterval(this.intervalHandle)
        this.emit('timeout')
      } else {
        this.emit('tick', this.countdown)
      }
    }, 1000)
  }

  stop() {
    clearInterval(this.intervalHandle)
    this.emit('stop', this.countdown)
  }

  reset() {
    this.stop()
    this.countdown = this.seconds
    this.emit('reset', this.countdown)
  }
}
