const logger = require('../logger');

class Queue {
  constructor(logger) {
    this.logger = logger;
    this.keys = [];
    this.tasks = [];
    this.currentTask = null;
  }


  add(key, task) {
    const index = this.keys.indexOf(key);
    if (index > -1) {
      this.tasks[index] = task;
    } else {
      this.keys.push(key);
      this.tasks.push(task);
    }
    this.logger.info("[!] - Added to queue : ", this.keys.length);
  }

  run() {
    if (!this.running)
      setTimeout(() => this.execIt(), 0);
  }

  async execIt() {
    if (this.tasks.length > 0) {
      this.currentTask = this.tasks.shift();
      this.keys.shift();
      this.running = true;
      await this.currentTask();
      setTimeout(() => this.execIt(), 0);
    } else {
      this.running = false;
    }
  }
}

module.exports = new Queue(logger);