// initialize everything, web server, socket.io, filesystem, johnny-five
var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  , five = require("johnny-five")
  , sensorLib = require('node-dht-sensor'),
  board,servo,led,sensor0,sensor1,sensor2,temp,hum;

board = new five.Board();

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

  // init a led on pin 13, strobe every 1000ms
  led = new five.Led(13);

  // setup a stanard servo, center at start
  servo = new five.Servo({
    pin:6,
    range: [0,180],
    type: "standard",
    center:true
  });

  // poll this sensor every second
  sensor0 = new five.Sensor({
    pin: "A0",
    freq: 1000
  });

  // poll this sensor every second
  sensor1 = new five.Sensor({
    pin: "A1",
    freq: 1000
  });

  // poll this sensor every second
  sensor2 = new five.Sensor({
    pin: "A2",
    freq: 1000
  });

  sensor2.within([ 0, 500 ], function() {
  	led.on();
  });

  sensor2.within([ 501, 1023 ], function() {
  	led.off();
  });

});

//read temperatur & humidity
var dht_sensor = {
    initialize: function () {
        return sensorLib.initialize(11, 4);
    },
    read: function () {
        var readout = sensorLib.read();
        console.log('Temperature: ' + readout.temperature.toFixed(2) + 'C, ' +
            'humidity: ' + readout.humidity.toFixed(2) + '%');
        temp = readout.temperature.toFixed(2);
        hum = readout.humidity.toFixed(2)
        setTimeout(function () {
            dht_sensor.read();
        }, 1000);
    }
};
 
if (dht_sensor.initialize()) {
    dht_sensor.read();
} else {
    console.warn('Failed to initialize sensor');
}

// make web server listen on port 80
app.listen(8080);


// handle web server
function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}


// on a socket connection
io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
 
  // if board is ready
  if(board.isReady){
    // read in sensor data, pass to browser
    sensor0.on("data",function(){
      socket.emit('sensor0', { raw: this.raw });
    });
    // read in sensor data, pass to browser
    sensor1.on("data",function(){
      socket.emit('sensor1', { raw: this.raw });
    });
    // read in sensor data, pass to browser
    sensor2.on("data",function(){
      socket.emit('sensor2', { raw: this.raw });
    });
  }

  // if servo message received
  socket.on('servo', function (data) {
    console.log(data);
    if(board.isReady){ servo.to(data.pos);  }
  });
  // if led message received
  socket.on('led', function (data) {
    console.log(data);
     if(board.isReady){    led.strobe(data.delay); } 
  });
  // if led-on/off message received
  socket.on('led-stop-blinking', function (data) {
    console.log(data);
     if(board.isReady){    led.stop(); } 
  });
  // if led-on message received
  socket.on('led-on', function (data) {
    console.log(data);
     if(board.isReady){    led.on(); } 
  });
  // if led-off message received
  socket.on('led-off', function (data) {
    console.log(data);
     if(board.isReady){    led.off(); } 
  });
  // if temp+hum received
  socket.on('temp+hum_req', function (data) {
    console.log(temp);
    console.log(hum);
    socket.emit('temp+hum_out', { temp_out: temp, hum_out: hum });
  });

});