var five = require("../lib/johnny-five.js");
var board = new five.Board();

board.on("ready", function() {

  var volume = 0;
  var previous = 0;
  var listen = null;
  var microphone = new five.Sensor.Analog("A0");
  var start = 0;

  var peak = 0;
  var max = 0;
  var min = 1024;
  var volts = 0;

  // Sample 25mhz (~40 readings per second)
  microphone.on("data", function() {
    var value = this.value;

    if (start === 0) {
      start = Date.now();
    }

     if (value > max) {
        // save just the max levels
        max = value;
     }
     if (value < min) {
        // save just the min levels
        min = value;
     }

    if (Date.now() >= start + 1000) {
      peak = max - min;
      volts = (peak * 5) / 1024;

      console.log( "tick", volts );
      start = 0;
      volts = 0;
    }
  });

  // microphone.on("change", function() {
  //   var value = this.value - 760;

  //   if (value < 0) {
  //     return;
  //   }

  //   volume = Math.abs(value);

  //   if (volume > 100 && volume !== previous && listen === null) {
  //     listen = Date.now();
  //     previous = volume;
  //   }

  //   if (listen !== null && Date.now() >= listen + 225) {
  //     console.log( "Beep" );
  //     listen = null;
  //   }
  // });
});
