import { Container, Point, Text, TextStyle } from 'pixi.js'
import { createText, timerStyle } from './utilities/fonts'

import { gsap } from 'gsap'

export class TimerText extends Container {
  private intervalHandle?: any
  private text?: Text
  animation: boolean = false
  textStyle: TextStyle = timerStyle()
  private countdown: number = 0
  private isInitiated: boolean = false

  constructor(
    private seconds: number,
    private point: Point,
  ) {
    super()
    this.countdown = seconds
    this.render()
  }

  reset() {
    this.stop()
    this.countdown = this.seconds
    this.isInitiated = false
    this.render()
  }

  start() {
    clearInterval(this.intervalHandle)
    this.isInitiated = true
    this.removeChildren()
    this.render()
    this.intervalHandle = setInterval(() => {
      this.countdown--
      !this.animation && this.text?.destroy()
      this.render()
      if (this.countdown === 0) {
        clearInterval(this.intervalHandle)
        this.emit('timeout')
      }
    }, 1000)
  }

  destroy() {
    this.stop()
    this.destroy()
  }

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

  private render() {
    if (!this.animation) this.removeChildren()
    this.text = createText({
      text: this.countdown.toString(),
      x: this.point.x,
      y: this.point.y,
      style: this.textStyle,
      container: this,
    })
    this.text.scale.set(1)
    if (this.animation && this.isInitiated) this.animate(this.text)
  }

  private animate(text: Text) {
    if (text) {
      gsap.timeline().to(text, {
        delay: 0.5,
        duration: 1.2,
        x: this.point.x + 2,
        y: this.point.y - 25,
        ease: 'power4.out',
        alpha: 0.0,
        onComplete: () => {
          text.destroy()
        },
        // scale: 1,
      })
      // gsap.to(this.text, {
      //   duration: 1,
      //   alpha: 0,
      //   x: this.app.canvas.width / 2,
      //   y: this.app.canvas.height / 2 - 20,
      //   scale: 1.3,
      //   ease: 'linear',
      // })
    }
  }
}
