var 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');

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

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

main = function() {
  var defPath;
  program.option('--broker <uri>', 'Broker address', String, '').option('--role <role>', 'Role of this instance', String, '').option('--interval <SECONDS>', 'How often to send discovery message', Number, 60).option('--forever <true>', 'Keep running forever', Boolean, false).usage('[options] <definition>').parse(process.argv);
  program = common.normalizeOptions(program);
  console.error("DEPRECATED: Instead use msgflo-register --role A:./filename.yaml - which also supports multiple roles");
  defPath = path.resolve(process.cwd(), program.args[0]);
  return fs.readFile(defPath, 'utf-8', function(err, contents) {
    var definition, e, messaging;
    if (err) {
      return onError(err);
    }
    if (!contents) {
      return onError(`No definition found in ${defPath}`);
    }
    try {
      definition = yaml.safeLoad(contents);
    } catch (error) {
      e = error;
      return onError(e);
    }
    if (!definition.component) {
      return onError(new Error(".component is not defined"));
    }
    if (program.role) {
      definition.role = program.role;
    }
    if (!definition.role) {
      return onError(new Error(`.role is not defined for component ${definition.component}`));
    }
    if (!definition.id) {
      definition.id = definition.role;
    }
    definition = foreigner.mapPorts(definition);
    messaging = msgflo_nodejs.transport.getClient(program.broker);
    return messaging.connect(function(err) {
      if (err) {
        return onError(err);
      }
      return foreigner.register(messaging, definition, function(err) {
        if (err) {
          return onError(err);
        }
        console.log('Sent discovery message for', definition.id);
        if (program.forever) {
          console.log('--forever enabled');
          return setInterval(function() {
            return foreigner.register(messaging, definition, function(err) {
              if (err) {
                return console.log('Warning: Failed to send discovery message:', err);
              }
            });
          }, program.interval * 1000 / 2.2);
        } else {
          return onComplete();
        }
      });
    });
  });
};

exports.main = main;
