export interface AnimationQueueObject {
  context: any;
  func: (...args: any[]) => Promise<any>;
  args: any[];
}

export class AnimationQueue {
  private running = false;
  private queue: AnimationQueueObject[] = [];

  push(o: AnimationQueueObject): void {
    if (this.running) {
      this.queue.push(o);
    } else {
      this.running = true;
      this.animate(o);
    }
  }

  animate(o: AnimationQueueObject): void {
    const self = this;
    try {
      (o.func.apply(o.context, o.args) as Promise<any>)
        .then(() => {
          if (self.queue.length > 0) {
            self.animate.call(self, self.queue.shift());
          } else {
            self.running = false;
          }
        })
        .catch(reason => {
          console.log(reason);
        });
    } catch (e) {
      console.log(e);
    }
  }

  clear(): void {
    this.queue = [];
  }
}
