var common, main, msgflo_nodejs, onComplete, onError, program;

program = require('commander');

msgflo_nodejs = require('msgflo-nodejs');

common = require('../common');

onError = function(err) {
  console.log(err);
  return process.exit(1);
};

onComplete = function() {
  return process.exit(0);
};

main = function() {
  var messaging, received;
  program.option('--broker <uri>', 'Broker address', String, null).option('--queue <name>', 'Queue to dump messages from', String, '').option('--amount <number>', 'How many messages to dump', Number, 1).parse(process.argv);
  program = common.normalizeOptions(program);
  received = 0;
  messaging = msgflo_nodejs.transport.getClient(program.broker, {
    prefetch: 1
  });
  return messaging.connect(function(err) {
    var onResult, packetsReceived;
    if (err) {
      return onError(err);
    }
    packetsReceived = [];
    onResult = function(msg) {
      packetsReceived.push(msg.data);
      messaging.ackMessage(msg);
      if (!(packetsReceived.length >= program.amount)) {
        return;
      }
      if (program.amount === 1) {
        console.log(JSON.stringify(packetsReceived[0]));
      } else {
        console.log(JSON.stringify(packetsReceived));
      }
      return messaging.disconnect(function(disconnectErr) {
        if (disconnectErr) {
          return onError(disconnectErr);
        }
        return onComplete();
      });
    };
    return messaging.subscribeToQueue(program.queue, onResult, function(err) {
      if (err) {
        return onError(err);
      }
    });
  });
};

exports.main = main;
