const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

/*const { Server } = require("socket.io");
const io = new Server(server);*/

const io = require("socket.io")(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

//variable para guardar los logs
var connections = [];

app.get('/', (req, res) => {
    //res.send('<h1>Hola mundo</h1>');
    res.sendFile(__dirname + '/index.html');
});

app.get('/adm', (req, res) => {
    res.sendFile(__dirname + '/adm.html');
});

io.on('connection', (socket) => {
    socket.on('register', (msg) => {
        if(connections.length == 0){
            connections.push(`${msg}.${socket.id}`);
        }else{
            var i = 0;
            var registered = false;

            do{
                connArr = connections[i].split(".");
                
                if(connArr[1] == socket.id){
                    registered = true;
                }
                
                i++;
            }while(i < connections.length && !registered);

            if(!registered) connections.push(`${msg}.${socket.id}`);
        }
        
        io.emit('new_connection', JSON.stringify(connections));
    });

    socket.on('unregister', (msg) => {
        let i = 0;
        let indexes = [];

        while(i < connections.length){
            connArr = connections[i].split(".");

            if(connArr[0] == msg){
                indexes.push(i);
            }

            i++;
        }

        if(indexes.length > 0){
            indexes.forEach(item => connections.splice(item, 1));
            io.emit('disconnection', JSON.stringify(connections));
        }
    });

    socket.on('disconnect', () => {
        let i = 0;
        let index = -1;
        while(i < connections.length){
            let element = connections[i];
            let elementArr = element.split(".");

            if(elementArr[1] == socket.id) index = i;

            i++;
        }

        if(index > -1) connections.splice(index, 1);
        io.emit('disconnection', JSON.stringify(connections));
    });

    socket.on('get_connections', () => {
        io.emit('current_connections', JSON.stringify(connections));
    });

    socket.on('profile_updated', (msg) => {
        io.emit('refresh_permissions', msg);
    });
});

server.listen(3200, () => {
    console.log('listening on *:3200');
});