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

  , obj = JSON.parse(fs.readFileSync('public/push.json', 'utf8'))

  , 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')
  , tankpush = 0
  , showerpush = 0

  , five = require("johnny-five")
  , sensorLib = require('node-dht-sensor')
  , scale = 500,
  board,servo,led,sensor0,sensor1,sensor2,temp,hum;

console.log(obj)

const webpush = require('web-push');

webpush.setVapidDetails(
  'mailto:info@baron-media.com',
  'BJyK9Nsetpbp9EkN1pPn-pGIuImquypJI1x_Dh77gXoxOu4wZDTOx7_glTvc5thBkKQtjMA--Phpww9LndDPP7k',
  'nK7VZSsSIGhijSK34-dNvGsgQ7Kp4uf2IpKGv61BtCA'
);

const pushSubscription = obj;

// 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
  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();
    if (showerpush===1) { 
      webpush.sendNotification(pushSubscription, 'Willy wurde fertig gegossen');
      console.log("send Push");
      console.log(scale);
      showerpush = 0;

    }
  });

  sensor2.within([ 500, 1023 ], function() {
  	led.off();
    if (showerpush===0) { 
      webpush.sendNotification(pushSubscription, 'Willy wird jetzt gegossen');
      console.log("send Push");
      showerpush = 1;
    }
  });

  sensor1.within([ 999, 1023 ], function() {
    if (tankpush===0) { 
      webpush.sendNotification(pushSubscription, 'Der Wassertank ist leer');
      console.log("send Push");
      tankpush = 1;
    }
  });

  sensor1.within([ 0, 998 ], function() {
    if (tankpush===1) { 
      webpush.sendNotification(pushSubscription, 'Der Wassertank wurde aufgefüllt');
      console.log("send Push");
      tankpush = 0;
    }
  });

});

//read temperatur & humidity
var dht_sensor = {
    initialize: function () {
        return sensorLib.initialize(11, 4);
    },
    read: function () {
        var readout = sensorLib.read();
        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');
}

// 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 scale message received
  socket.on('scale', function (data) {
    console.log(data);
    scale = data.Scale;
    console.log(scale);
    console.log(scale+1);
  });
  // 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 });
  });
  socket.on('push', function (data) {
    webpush.sendNotification(pushSubscription, 'Your Push Payload Text');
  });

});