var Board = require("../");

Board.requestPort(function(error, port) {
  if (error) {
    console.log(error);
    return;
  }

  var register = {
    POWER: 0x20,
    RANGE: 0x31,
    ACCELEROMETER_READ: 0x28,
  };

  var board = new Board(port.comName);

  board.on("ready", function() {
    console.log("Ready");

    var buffer = new Buffer(6);
    var lsm303 = 0x19;
    var sensitivity = 0.001;
    var gravity = 9.80665; // m/s^2

    // Enable I2C
    this.i2cConfig();

    // Power up and enable the accelerometer
    this.i2cWrite(lsm303, register.POWER, 0x57);


    // Set range (this is 2G range)
    // this.i2cWrite(lsm303, register.RANGE, 8);

    // Set register to ACCELEROMETER_READ (with subaddress updating) and request 6 bytes
    this.i2cRead(lsm303, register.ACCELEROMETER_READ | (1 << 7), 6, function(data) {

      // buffer.splice(0, 6, (data)
      // These come out LSB first...
      var x = (data[1] << 8) | data[0];
      var y = (data[3] << 8) | data[2];
      var z = (data[5] << 8) | data[4];

      var X = x * sensitivity * gravity;
      var Y = y * sensitivity * gravity;
      var Z = z * sensitivity * gravity;

      console.log("X: ", X);
      console.log("Y: ", Y);
      console.log("Z: ", Z);

      this.i2cStop(lsm303);
    }.bind(this));
  });

  process.on("SIGINT", _ => {
    board.reset();
    process.exit();
  });
});
