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

  var router = require('router');

  var binPins = ["IN0", "IN1"];

  function BinaryInputNode(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.pin = n.pin;
    this.active = (n.active == 'low' ? 0 : 1);

    if (n.outputOn === "rising") {
      this.activeEdges = [false, true];
    } else if (n.outputOn === "falling") {
      this.activeEdges = [true, false];
    } else if (n.outputOn === "both") {
      this.activeEdges = [true, true];
    } else {
      node.error("Invalid edge type: " + n.outputOn);
    }

    this.updateInterval = n.updateInterval;    // How often to send totalActiveTime messages
    // Working variables
    this.intervalId = null;         // Remember the timer ID so we can delete it when we are closed
    this.currentState = 0;          // The pin input state "1" or "0"

    var timerCallback = function () {

      if (binPins.indexOf(node.pin) >= 0) {

        if (node.pin === 'IN0') {
          node.currentState = router.bIn[0];
        } else if (node.pin === 'IN1') {
          node.currentState = router.bIn[1];
        }
        node.currentState = Number(node.currentState != node.active);

        if (node.currentState !== node.activeState) {

          if (node.activeEdges[node.currentState]){

            var msg = {};
            msg.payload = Number(node.currentState);
            node.send(msg);

          }

          node.activeState = node.currentState;

        }
      }
    };

    node.intervalId = setInterval(timerCallback, node.updateInterval);

  }

  function BinaryOutputNode(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.pin = n.pin;                               // The pin identifying string
    this.initial = Number(n.initial);               // What state to set up as
    this.inverting = n.inverting;

    node.on("input", (msg) => {
      var newState = (msg.payload ? true : false);
      newState = (node.inverting ? !newState : newState);
      router.bOut[0] = Number(newState);
    });

    router.bOut[0] = this.initial;
  }

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