const express = require('express');
const WebSocket = require('ws');

// App setup
var app = express();

var server = app.listen(4000, function () {
    console.log('listening for requests on port 4000.');
});

var peerMap = new Object();

// Static files
app.use(express.static('.'));

const wss = new WebSocket.Server({ server });

wss.on('connection', function(ws) {
    ws.on('message', function(message) {
        // Broadcast any received message to all clients
        console.log('received: %s', message);

        var recievedObject = JSON.parse(message);

        if (recievedObject.getPeerMap){
            recievedObject.peerMap = peerMap;
            recievedObject.nofPeers = Object.keys(peerMap).length;
            message = JSON.stringify(recievedObject)
        }

        if (typeof(peerMap[recievedObject.uid]) === 'undefined'){
            peerMap[recievedObject.uid] = [];
            console.log('new peer object created');
        }

        if(typeof(recievedObject.sdp) !== 'undefined'){
            peerMap[recievedObject.uid][0] = recievedObject.sdp.sdp;
            console.log('add sdp to peer ' + recievedObject.uid);
        }

        if(typeof(recievedObject.ice) !== 'undefined'){
            peerMap[recievedObject.uid][1] = recievedObject.ice.candidate;
            console.log('add ice to peer ' + recievedObject.uid);
        }

        console.log('modified message ' + message);

        wss.broadcast(message);
    });
});

wss.broadcast = function(data) {
    this.clients.forEach(function(client) {
        if(client.readyState === WebSocket.OPEN) {
            client.send(data);
        }
    });
};

console.log('Server running.');