const WebSocket = require('ws');
var http = require('http');
const fs = require('fs');

var websocket_port = 8888;
const wss = new WebSocket.Server({port: websocket_port});
console.log("Websocket server running on port " + websocket_port);

var lookup = [];

wss.on('connection', function connection(ws) {
    lookup[ws.protocol] = ws;
});
/*{
 cert: fs.readFileSync('/etc/letsencrypt/live/atcheck.projektstudencki.pl/cert.pem'),
 key: fs.readFileSync('/etc/letsencrypt/live/atcheck.projektstudencki.pl/privkey.pem')
 }, */
var server = http.createServer(function (request, response) {
    response.writeHead(200, {"Content-Type": "text\plain"});
    request.setEncoding('utf8');

    if (request.method === "POST") {
        var body = '';

        request.on('data', function (chunk) {
            body += chunk;
        });
        try {
            request.on('end', function () {
                body = body.split("&");
                var send_array = {
                    "type": "data",
                    "id": body[1],
                    "name": body[2],
                    "surname": body[3],
                    "classes_code": body[0]
                };
                lookup[body[0]].send(JSON.stringify(send_array));
            });
        } catch (e) {console.log(e)}
    }
    else {
        response.end("Undefined request .");
    }
});

var http_port = 8889;
server.listen(http_port);
console.log("HTTP server running on port " + http_port);