require('dotenv').config();
const ws = require('ws');
let server = require('http').createServer();


const wsServer = new ws.Server({
    server: server
});

const wsBroadcast = (message) => {
    wsServer.clients.forEach(client => {
        if (client.readyState === ws.OPEN) {
            client.send(message);
        }
    });
}

const startWebSocket = (server) => {
    wsServer.on('connection', function connection(ws) {
        ws.on('message', function incoming(message) {
            console.log(`received: ${message}`);
        });
        ws.on('error', function (e) { return console.log(e); });
        ws.on('close', function (e) { return console.log('websocket closed ' + e); });
    });

    server.on('upgrade', (request, socket, head) => {
        wsServer.handleUpgrade(request, socket, head, socket => {
            wsServer.emit('connection', socket, request);
        });
    });
}

module.exports = { startWebSocket, wsBroadcast };
