var WebSocketServer = require('websocket').server;
var http = require('http');

var server = http.createServer(function(request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});
server.listen(8080, function() {
    console.log((new Date()) + ' Server is listening on port 8080');
});

wsServer = new WebSocketServer({
    httpServer: server,
    // You should not use autoAcceptConnections for production
    // applications, as it defeats all standard cross-origin protection
    // facilities built into the protocol and the browser.  You should
    // *always* verify the connection's origin and decide whether or not
    // to accept it.
    autoAcceptConnections: false
});
wsServer.clients = [];
function originIsAllowed(origin) {
    // put logic here to detect whether the specified origin is allowed.
    console.log("origin : " + origin);
    return origin === "http://localhost:3000";
}

wsServer.on('request', function(request) {

    wsServer.broadcast = function broadcast(message) {
        wsServer.clients.forEach((client) => {
            client.send(message);
        });
    };

    if (!originIsAllowed(request.origin)) {
        // Make sure we only accept requests from an allowed origin
        request.reject();
        console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.');
        return;
    }
    var connection = request.accept('echo-protocol', request.origin);
    console.log(request);
    console.log((new Date()) + ' Connection accepted.');
    //clients.push(request.client);
  //  console.log("client : ", request.clients);
  //  console.log("clients : ", connection.);
    wsServer.clients.push(connection);
    function sendDate() {
        var json = JSON.stringify({date : new Date()});
     /*   var date = new Date().getTime();
        // create an ArrayBuffer with a size in bytes
        const buffer = new ArrayBuffer(72);
        // Create a couple of views
        const data = new BigInt64Array(2);
        const view1 = new DataView(buffer);
        view1.setBigInt64(0, BigInt(date));
        view1.setInt8(64, Math.random() * 10);
        data[0] = view1.getBigInt64(0);
        data[1] = BigInt(view1.getInt8(64));*/
        wsServer.broadcast(json);
        setTimeout(sendDate, 20000);
    }
    sendDate();

    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log('Received Message: ' + message.utf8Data);
            connection.sendUTF(message.utf8Data);

        }
        else if (message.type === 'binary') {
            console.log('Received Binary Message of ' + message.binaryData.length + ' bytes');
            connection.sendBytes(message.binaryData);
        }
    });
    connection.on('close', function(reasonCode, description) {
        console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
    });
});
