//Loading dependencies & initializing express
var os = require('os');
var express = require('express');
var app = express();
const path = require('path');
//For signalling in WebRTC
var socketIO = require('socket.io');
const fs = require('fs');
const cors = require('cors');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
const webpush = require('web-push');
const https = require('https');


app.use(cors({
    origin: 'https://p2share.me:3333'
}));

const server = https.createServer({

        cert: fs.readFileSync("/home/ferrane/claus/fullchain.pem"),

        key: fs.readFileSync("/home/ferrane/claus/privkey.pem"),

}, app).listen(3000, function() { console.log('https web server (signaling + html) is listening on *: 3000')});

const publicVapidKey = "BK8cnyTGqgS7KbiqNoT3tYQgiDXplgnumSPKijvFeqnDKf9u1PJNy6NBeIZKy2FaU2V3MrgUG_ErjkuZWmRJqsQ";
const privateVapidKey = "JEKRYitQEO8LJaa4NCuKgDx7CQCLgHNsbfEHd3Ke6_0";

webpush.setVapidDetails("mailto:ferrane98@gmail.com", publicVapidKey, privateVapidKey);

app.post('/subscribe', (req, res) => {
    const subscription = req.body;
    res.status(201).json({});
    const payload = JSON.stringify({ title: "P2SHARE.ME", body: "If you recieved this notification your device has been added correctly.", data:'subscribe' });
    webpush.sendNotification(subscription, payload).catch(console.log);
})

app.post('/push', (req, res) => {
	var cos = 'Click to Enter the Room: ' + req.body.room;
    res.status(201).json({});
    const payloadPush = {
      title: 'P2SHARE',
      renotify: true,
      body: cos,
      data: req.body.room
};

    webpush.sendNotification(JSON.parse(req.body.subscription), JSON.stringify(payloadPush)).catch(console.log);
})

// 1) El servidor web https com a servidor web de l'HTML+JS

const publicPath = path.resolve(__dirname, 'public');

app.use(express.static(publicPath));

app.get('/', (req, res) => {

  res.sendFile(__dirname + '/index.html');

});
app.get('/reciever.html', (req, res) => {

	res.sendFile(__dirname + '/reciever.html');
  
});
app.get('/sender.html', (req, res) => {

	res.sendFile(__dirname + '/sender.html');
  
});

var io = socketIO(server);

io.sockets.on('connection', function(socket) {

	// Convenience function to log server messages on the client.
	// Arguments is an array like object which contains all the arguments of log(). 
	// To push all the arguments of log() in array, we have to use apply().
	function log() {
	  var array = ['Message from server:'];
	  array.push.apply(array, arguments);
	  socket.emit('log', array);
	}
  
    
    //Defining Socket Connections
    socket.on('message', function(message, room) {
	  log('Client said: ', message);
	  // for a real app, would be room-only (not broadcast)
	  socket.in(room).emit('message', message, room);
	});
  
	socket.on('create or join', function(room) {
	  log('Received request to create or join room ' + room);
  
      var clientsInRoom = io.sockets.adapter.rooms.get(room);

      var numClients = clientsInRoom ? clientsInRoom.size : 0;
      log("Room " + room + " now has " + numClients + " client(s)")
  
	  if (numClients === 0) {
		socket.join(room);
		log('Client ID ' + socket.id + ' created room ' + room);
		socket.emit('created', room, socket.id);
  
	  } else if (numClients === 1) {
		log('Client ID ' + socket.id + ' joined room ' + room);
		io.sockets.in(room).emit('join', room);
		socket.join(room);
		socket.emit('joined', room, socket.id);
		io.sockets.in(room).emit('ready');
	  } else { // max two clients
		socket.emit('full', room);
	  }
	});
  
	socket.on('ipaddr', function() {
	  var ifaces = os.networkInterfaces();
	  for (var dev in ifaces) {
		ifaces[dev].forEach(function(details) {
		  if (details.family === 'IPv4' && details.address !== '127.0.0.1') {
			socket.emit('ipaddr', details.address);
		  }
		});
	  }
	});
  
	socket.on('bye', function(){
	  console.log('received bye');
	});
  
  });
