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

  var router = require('router');

  function HardwareMonitor(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.param = n.param;
    this.when = Number(n.when);
    this.low = (n.low == "" ? undefined : Number(n.low));
    this.high = (n.high == "" ? undefined : Number(n.high));

    this.lastValue = null;

    // Regulary called check
    this.intervalId = setInterval(() => {
      // Get current value
      var value;
      switch (node.param) {
        case 'temperature':
          value = router.temperature;
          break;
        case 'voltage':
          value = router.powerSupply;
          break;
        default:
          value = null;
      }
      //console.log("VALUE: "+value+" RANGE: "+node.low+":"+node.high+" EVENT: "+node.when+"\n");

      // Compare value
      if (value != node.lastValue) {
        if ((node.when == 0) ||                                                                           // any change
            (node.when == 1 && (!node.low || value >= node.low) && (!node.high || value <= node.high)) || // in range
            (node.when == -1 && ((node.low && value < node.low) || (node.high && value > node.high))) )   // out of range
        {
          // Send message
          var msg = {};
          msg.payload = value;
          node.send(msg);
        }
      }

      node.lastValue = value;
    }, 1000);

    this.on("close", () => {
      clearInterval(node.intervalId);
    });
  }

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