module.exports = function(RED) {
  "use strict";

  var xbus = require('router').XBus;

  function XBusSubscriberNode(n) {
    // Create a RED node
    RED.nodes.createNode(this, n);

    var node = this;

    // Store local copies of the node configuration (as defined in the .html)
    this.topic = n.topic;             // topic

    // Subscribe to topic
    this.subscribeId = xbus.subscribe(this.topic, (xmsg) => {
      // Send message to node output
      var msg = {};
      msg.topic = xmsg.topic;
      msg.payload = xmsg.payload;
      node.send(msg);
    });

    // Unsubscribe on object destroy
    this.on("close", () => {
      xbus.unsubscribe(node.subscribeId);
    });
  }

  function XBusPublisherNode(n) {
    // Create a RED node
    RED.nodes.createNode(this, n);

    var node = this;

    // Store local copies of the node configuration (as defined in the .html)
    this.topic = n.topic;             // topic

    node.on("input", (msg) => {
      xbus.publish((msg.topic ? msg.topic : node.topic), msg.payload);
    });
  }

  // Register the node by name. This must be called before overriding any of the
  // Node functions.
  RED.nodes.registerType("xbus_subscriber", XBusSubscriberNode);
  RED.nodes.registerType("xbus_publisher", XBusPublisherNode);
}
