#!/usr/bin/env node

var child = require('child_process');
var myREPL = child.spawn('node');
var util = require('util');
var app = require('express')();
var serialport = require('serialport');
var Serial = serialport.SerialPort;
var maxWait = 5000;

var startTime = new Date().setMinutes(0);

var serialPort = new Serial('/dev/ttyUSB0', {

    baudrate: 38400, //baud rate of the xbee
    //right now delimiter is a space    
    parser: serialport.parsers.raw

}, true);

var readPins = [5];
var writePins = [8, 9];
gpio.setup(readPins[0], gpio.DIR_IN, readInput);

//read to a pin
function readInput(){
  gpio.read(readPins[0], function(err, value){
    if(err){
      console.log('error: ' + err);
    }
    console.log("the value(s) are: ", value);
  });
}

//Listen for Changes
gpio.on('change', function(channel, value){
  console.log("channel " + channel + "value is now " + value);
});

//destroy pins
function pause(){
  setTimeout(closePins, 2000);
}
function closePins(){
  gpio.destroy(function(){
    console.log("All pins destroyed");
    return process.exit(0);
  });
}

/
//log serial port to see if pipe is good 
function cb(){
  console.log("calling back");
}

serialPort.on('open', function(err) { //opens the serial port
  
  if(err) throw("Error: ", err);
  console.log("open");
});

serialPort.on('data', function(data, err) {
  
  if(err) throw("Error: ", err);   
  writeDrain(data, cb);    
});

function writeDrain(data, cb) {
  
  var nowTime = ((new Date().getMinutes()) - startTime); 
 
  serialPort.pause();

  serialPort.flush(function(){
    console.log("flushed");   
    
    setTimeout(function(){
      console.log("\n");
      serialPort.resume();
    }, 500)
    
  var dataToAdd = {
      event:        data[0],
      frequency:    data[1],
      addressH:     data[2],
      addressL:     data[3],
      timeStamp:    nowTime
  };
 
  console.log(util.inspect(dataToAdd, {showHidden: false, depth: null}) + '\n');
  serialPort.write("data" + dataToAdd, function(err){
    
    if(err) throw("error: " + err);
    outStream.once('open', function(fd){
      stream.write(dataToAdd + '\n');
    });    
    if(err) throw "error: " + err;
  });
 })
}
