var logger = require('./logger.js');

var CommandRing = function() {
  var that = this;
  var tasks = []
  this.running = false;

  this.push = function(command, callback) {
    tasks.push(command);
    tasks[tasks.length - 1].start(callback);
    logger.debug("Added command to ring");
    if (!that.running) {
      that.run();
    }
    callback();
  };

  this.stop = function() {
    logger.debug("stopping command ring");
    that.running = false;
  };

  this.tasks_by_name = function() {
    return tasks.map(function(task) {
      return task.name;
    });
  };
    

  this.inspect = function() {
    names = tasks.map(function(task) {
      return task.name;
    });

    return "Tasks: " + names.join(", ");
  };

  this.run = function() {
    that.running = true;
       
    tasks.each_with_index(function(task, i) {
      if (task.status == 'done') {
        logger.debug("Done with: " + task.name);
        tasks[i] = null
      } else {
        logger.debug("Status of " + task.name + ": " + task.status);
      }
    });

    tasks = tasks.filter(function(n){ 
      return n != undefined });

    if (!tasks.length) {
      logger.debug("Command ring is empty");
      that.stop();
    }

    setTimeout(function() {
      if (that.running) that.run();
    }, 5000);

  };
};


module.exports = CommandRing;
