require('./utils.js');

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

var Command = require('./command.js');
var CommandRing = require('./command_ring.js');
var ring = new CommandRing();

var prompt = require('./prompt_chain.js');

var commands = {
  session: Command('session', function(progress) {
    console.log("Session: " + config.session);
    progress('done');
  }),

  hello: Command('hello', function(progress) {
    var that = this;
    progress('clear');
    respond("said hello");
    setTimeout(function() {
      progress('done');
    }, 20000);

  }),

  setup: Command('setup', function(progress) {
    prompt.get([{
      description: 'ArchivesSpace Backend URL',
      name: 'backend_url',
      pattern: /^http/,
      type: 'string',
      required: true,
      default: config.backend_url,
    }, {
      name: 'user',
      description: 'Your username',
      type: 'string',
      required: true,
      default: 'admin',
    }, {
      name: 'password',
      hidden: true,
    }], function(err, result) {

      api.login(result, function(err, session) {
        if (err) {
          respond(err);
        } else {
          config.backend_url = result.backend_url;
          config.session = session;
          config.save();
          respond("You are logged in");
        }
      });
    });
  }),
};


function respond(message) {
  console.log(message);
  prompt.reset();
}
    

//var pq = new PromptQ(ring, commands);

//pq.start();

var loop = function() {

  prompt.get([{
    name: 'command',
    type: 'string',
  }], function(err, result) {
    logger.debug(result.command);
    if (result.command == 'exit') {
      exit();
    } else if (result.command == 'inspect') {
      console.log(ring.inspect());
      loop();
    } else {
      var command = new commands[result.command]();
      ring.push(command, function() {
//        loop();
      });
    }
  });

}

function exit() {
  if (ring.running) {
    console.log("Waiting for jobs to complete: " + ring.active_tasks_by_name().join(', '));
    setTimeout(function() {
      exit(); }, 1000);
  } else {
    console.log("Goodbye");
  }
}


function login(opts, callback) {

  var form = {form: {password: password}};
  var session = "";

  request.post(config.backend_host + ":" + config.backend_port + "/users/" + user + "/login", form, function(error, response, body) {
    json = JSON.parse(body);
    console.log(json);

    config.session = json.session;

    saveConfig(config_file, config);
  });
}


// prompt.start();
// loop();


prompt.get([{
  name: 'command',
  type: 'string',
}], function(err, result) {
  logger.debug(result.command);
  if (result.command == 'exit') {
    exit();
  } else if (result.command == 'inspect') {
    console.log(ring.inspect());
    loop();
  } else {
    var command = new commands[result.command]();
    ring.push(command, function() {
    });
  }
});

