

export interface Interpolator {
  getInterpolation(t: number): number;
}


export type AnimatorCallback = (animator : Animator) => void


export class Animator {


  private startTime: number = new Date().getTime()
  private _progress: number = 0
  public get progress() {
    return this._progress
  }

  private running: boolean = true
  private ended: boolean = false
  private canceled: boolean = false

  constructor(
    private duration: number,
    private onUpdate: AnimatorCallback,
    private onEnd: AnimatorCallback,
    private interpolator?: Interpolator
  ) {

  }

  update() {
    if (this.removable()) return

    const dur = new Date().getTime() - this.startTime
    if (dur < this.duration) {
        this._progress = dur / this.duration
        this.onUpdate(this)
    } else if (dur >= this.duration) {
        if (this.running) {
            this._progress = 1
            this.onUpdate(this)
            this.running = false
        } else {
            this.end()
        }
    }
}




  removable(): Boolean {
    return this.ended || this.canceled
  }


  cancel() {
    if (!this.canceled) {
      this.canceled = true
      this.end()
    }
  }



  end() {
    if (!this.ended) {
      this.onEnd(this)
      this.ended = true
    }
  }


  value(): number {
    if (this.interpolator != null) {
      return this.interpolator.getInterpolation(this._progress)
    } else {
      return this._progress
    }
  }





}
