// initialize everything, web server, socket.io, filesystem, johnny-five
var fs = require('fs')
  , https = require('https')

  , express = require('express')
  , app = express()

  , options = {
  	ca: fs.readFileSync('./file.ca'),
    key: fs.readFileSync('./file.pem'),
    cert:fs.readFileSync('./file.crt')
  }
  , serverPort = 443

  , server = https.createServer(options, app)

  , io = require('socket.io').listen(server)
  , Push = require('push.js')

  , five = require("johnny-five"),
  board,servo,led,sensor;

// make web server listen on port 80
server.listen(serverPort);
app.use(express.static('public')); //tell the server that ./public/ contains the static webpages


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

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


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
  sensor = new five.Sensor({
    pin: "A0",
    freq: 1000
  });

});

// 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
    sensor.on("data",function(){
      socket.emit('sensor', { 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 led-off message received
  socket.on('push', function (data) {
    Push.create("Hello world!", {
    body: "How's it hangin'?",
    icon: 'icon.png',
    timeout: 4000,
    onClick: function () {
        window.focus();
        this.close();
    }
}); 
  });

});