var Tinkerforge = require('../Tinkerforge')
,   Conf        = require('./config.json')
,   http        = require('http');

var HOST = Conf.host;
var PORT = Conf.port;
var UID = Conf.uid;

var ipcon = new Tinkerforge.IPConnection(); // Create IP connection
var ai = new Tinkerforge.BrickletAnalogInV2(UID, ipcon); // Create device object

var radicalChange = false;
var readyForNextNotification = true;

ipcon.connect(HOST, PORT,
  function (error) {
    console.log('Error: ' + error);
  }
); // Connect to brickd
// Don't use device before ipcon is connected

ipcon.on(Tinkerforge.IPConnection.CALLBACK_CONNECTED,
  function (connectReason) {
    // Set period for voltage callback to 1s (1000ms)
    // Note: The voltage callback is only called every second
    //       if the voltage has changed since the last call!
    ai.setVoltageCallbackPeriod(1000);

    console.log('Host: ' + Conf.host + ':' + Conf.port + ' connected');
  }
);

// Register voltage callback
ai.on(Tinkerforge.BrickletAnalogInV2.CALLBACK_VOLTAGE,
  // Callback function for voltage callback (parameter has unit mV)
  function (voltage) {
    var v = voltage/1000.0;
    console.log('Voltage: ' + v + ' V');

    if(v > 3) {
      if(readyForNextNotification) {
        radicalChange = true;
        readyForNextNotification = false;
        
        setTimeout(function() { readyForNextNotification = true; }, 10000);
      } else {
        radicalChange = false;
      }
    } else {
      radicalChange = false;
    }
    
    if(radicalChange) {
      doHoBuDoorBellCall();
    }
  }
);

process.on( 'SIGINT', function() {
  Log.log( "Gracefully disconnect " + HOST );
  ipcon.disconnect();
  process.exit( );
});


/* private */
function doHoBuDoorBellCall() {
  var options = {
    host: Conf.on.ring.host,
    port: Conf.on.ring.port,
    path: Conf.on.ring.path
  };

  callback = function(response) {
    var str = '';
  
    //another chunk of data has been recieved, so append it to `str`
    response.on('data', function (chunk) {
      str += chunk;
    });

    //the whole response has been recieved, so we just print it out here
    response.on('end', function () {
      console.log(str);
    });
  }

  var req = http.request(options, function(res) {
    //Log.inspect('Result', res);
  });
  
  req.on('error', function(err) {
    if(HOST) {
      Log.error(HOST + ': ' + err);
    } else {
      Log.error(err);
    }
  });
  
  req.end();
}