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

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

  function SMSReceiverNode(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.filter = (n.filter ? n.filter.trim().split(/\s+/) : undefined);    // the filter for phone numbers

    this.subscribeId = xbus.subscribe('sms/incoming', (xmsg) => {
      var sms = xmsg.payload.split('\n\n');
      var meta = sms[0].split('\n');

      // Propagate if phone number not filtered or match filter only
      if (!node.filter || node.filter.includes(meta[0].substr(6))) {
        var msg = {};
        msg.payload    = sms[1];
        msg.from       = meta[0].substr(6);           // "From: %s"
        msg.date       = new Date(meta[1].substr(6)); // "Date: %04u-%02u-%02u %02u:%02u:%02u"
        msg.authorized = (meta[2][6] == '1');         // "Auth: %u"

        node.send(msg);
      }
    });

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

  function SMSSenderNode(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.number = n.number;       // the phone number
    this.prepend = n.prepend;     // text prefixed to payload

    node.on("input", (msg) => {
    if (msg.payload && (this.number || msg.to)) {
        spawn('gsmsms', [(msg.to ? msg.to : this.number), this.prepend + msg.payload]);
      }
    });
  }

  // Register the node by name. This must be called before overriding any of the
  // Node functions.
  RED.nodes.registerType("sms_sender", SMSSenderNode);
  RED.nodes.registerType("sms_receiver", SMSReceiverNode);
}
