const { currentGame, resetGame } = require("./partyManager");
const { wsBroadcast } = require("./websocketManager");
const ws = require('ws');

const server = require('http').createServer(function (request, response) {
    console.log((new Date()) + ' Received request for ' + request.url);
    response.writeHead(404);
    response.end();
});

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


const options = { year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };
let keys = [];

let events = [
    (key, message, full, date) => {
        console.log(date.toLocaleDateString("en-FR", options) + ' - MESSAGE FROM: ' + key + ' -> ' + full)

        if (!keys.includes(key)) {
            keys.push(key);
        }
        console.log(currentGame.context());
    }
]

const startCommunication = () => {
    server.listen(process.env.PORT_UDP, function () {
        console.log('Websocket server is listening in port : ' + process.env.PORT_UDP);
    });
    wsServer.on('connection', function connection(ws) {
        ws.on('message', (message) => {
            console.log(message.toString());
            const split = (message + "").split(process.env.UDP_SEP);
            if (split[0] == process.env.SERVER_NAME && split.length >= 3) {
                for (e of events) {
                    e(split[1], split[2], message, new Date);
                }
            }

        });
        ws.on('error', function (e) { return console.log(e); });
        ws.on('close', function (e) { return console.log('websocket closed ' + e); });
    });

    addMessageListener((key, message, full, date) => {
        if (message == "CONNECT") {
            currentGame.addPlayer(key);
            sendMessageWithKey("SERVER_TEST", key);
        }
    });
    addMessageListener((key, message, full, date) => {
        if (message == "HIT") {
            if (currentGame.startTime && !currentGame.finishTime) {
                currentGame.addEvent(key);
                wsBroadcast(JSON.stringify({
                    message: {
                        key: key,
                        action: "HIT"
                    },
                    context: currentGame.context()
                }))
            }
        }
    });
    addMessageListener((key, message, full, date) => {
        if (message == "PONG") {
            currentGame.addPlayer(key);
        }
    });
}

function ping(id) {
    console.log(id);
    if (id) {
        sendMessageWithKey("PING", id);
    } else {
        sendMessageAll("PING");
    }
}

function addMessageListener(messageFunc) {
    events.push(messageFunc);
}

function addKeys(key) {
    keys.push(key);
}

function parseMessage(message) {
    return message + "";
}

function sendMessageWithKey(message, key) {
    const mes = key + process.env.UDP_SEP + process.env.SERVER_NAME + process.env.UDP_SEP + message;
    sendMessage(mes);
}

function sendMessageAll(message) {
    for (key of keys) {
        sendMessageWithKey(message, key);
    }
}

function sendMessage(message, date = new Date()) {
    console.log(date.toLocaleDateString("en-FR", options) + " - MESSAGE SEND : " + message);
    wsServer.clients.forEach(client => {
        if (client.readyState === ws.OPEN) {
            client.send(message);
        }
    });
}

module.exports = { startCommunication, addMessageListener, parseMessage, sendMessage, addKeys, ping, keys, sendMessageWithKey, sendMessageAll }

