var common, msgflo_nodejs, normalize, parse, program, sendData, validate;

program = require('commander');

msgflo_nodejs = require('msgflo-nodejs');

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

parse = function(args) {
  return program.option('--broker <uri>', 'Broker address', String, '').option('--queue <name>', 'Queue to dump messages from', String, '').option('--json <JSONDATA>', 'Data to send. Must be valid JSON', String, '').parse(args);
};

normalize = function(options) {
  options = common.normalizeOptions(options);
  return options;
};

validate = function(options) {
  var data, e;
  if (!options.queue) {
    throw new Error('Missing queue to send to (--queue)');
  }
  if (!options.json) {
    throw new Error('Missing message payload (--json)');
  }
  try {
    data = JSON.parse(options.json);
  } catch (error) {
    e = error;
    e.message = 'Invalid JSON: ' + e.message;
    throw e;
  }
  return data;
};

sendData = function(options, data, callback) {
  var client;
  client = msgflo_nodejs.transport.getClient(program.broker);
  return client.connect(function(err) {
    if (err) {
      return callback(err);
    }
    return client.sendTo('inqueue', options.queue, data, function(err) {
      if (err) {
        return callback(err);
      }
      return client.disconnect(function(err) {
        // ignore error, we sent succesfully anyways
        return callback(null);
      });
    });
  });
};

exports.main = function() {
  var data, e, options;
  options = parse(process.argv);
  options = normalize(options);
  try {
    data = validate(options);
  } catch (error) {
    e = error;
    console.log(e.message);
    process.exit(1);
  }
  return sendData(options, data, function(err) {
    if (err) {
      throw err;
    }
  });
};
