// retoor <retoor@molodetz.nl>
export default class Queue {
  constructor(onEmptyCallback) {
    this._queue = [];
    this._onEmptyCallback = onEmptyCallback;
    this._active = false;
  }

  queue(func) {
    this._queue.push(func);

    if (this._queue.length === 1 && !this._active) {
      this._progressQueue();
    }
  }

  _progressQueue() {
    if (!this._queue.length) {
      this._onEmptyCallback();
      return;
    }

    const func = this._queue.shift();
    this._active = true;

    const completeFunction = this.next.bind(this);
    func(completeFunction);
  }

  clear() {
    this._queue = [];
  }

  next() {
    this._active = false;
    this._progressQueue();
  }

  dispose() {
    this._queue = [];
    this._active = false;
    this._onEmptyCallback = () => {};
  }
}
