var Promise, collectMap, common, foreigner, fs, main, msgflo_nodejs, onComplete, onError, path, program, yaml;

program = require('commander');

msgflo_nodejs = require('msgflo-nodejs');

fs = require('fs');

path = require('path');

foreigner = require('../foreign-participant');

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

yaml = require('js-yaml');

Promise = require('bluebird');

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

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

collectMap = function(val, map) {
  var definition, role;
  [role, definition] = val.split(':');
  map[role] = definition;
  return map;
};

main = function() {
  var messaging, readFile, register;
  program.option('--broker <uri>', 'Broker address', String, '').option('--role <role:definition>', 'Map of roles and definition files', collectMap, {}).option('--interval <SECONDS>', 'How often to send discovery message', Number, 60).option('--forever <true>', 'Keep running forever', Boolean, true).usage('[options]').parse(process.argv);
  program = common.normalizeOptions(program);
  program.roles = program.role;
  readFile = Promise.promisify(fs.readFile);
  messaging = msgflo_nodejs.transport.getClient(program.broker);
  register = Promise.promisify(foreigner.register.bind(foreigner));
  return Promise.map(Object.keys(program.roles), function(role) {
    var defPath;
    defPath = path.resolve(process.cwd(), program.roles[role]);
    return readFile(defPath, 'utf-8').then(function(contents) {
      var definition;
      if (!contents) {
        return Promise.reject(`No definition found in ${defPath}`);
      }
      definition = yaml.safeLoad(contents);
      if (!definition.component) {
        return Promise.reject(new Error(".component is not defined"));
      }
      definition.role = role;
      if (!definition.id) {
        definition.id = definition.role;
      }
      definition = foreigner.mapPorts(definition);
      return Promise.resolve(definition);
    });
  }).then(function(definitions) {
    var connect;
    connect = Promise.promisify(messaging.connect.bind(messaging));
    return connect().then(function() {
      return Promise.map(definitions, function(definition) {
        return register(messaging, definition).then(function() {
          console.log('Sent discovery message for', definition.id);
          return Promise.resolve(definition);
        });
      });
    });
  }).then(function(definitions) {
    if (!program.forever) {
      onComplete();
    }
    return setInterval(function() {
      return Promise.map(definitions, function(definition) {
        return register(messaging, definition);
      }).asCallback(function(err) {
        if (err) {
          return console.log('Warning: Failed to send discovery message:', err);
        }
      });
    }, program.interval * 1000 / 2.2);
  });
};

exports.main = main;
