const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server, Socket } = require('socket.io');
const io = new Server(server);
const cors = require('cors');
const path = require('path');

app.use(cors());

var localstorage_session =  "";

var users_sessions = [];



app.use(express.static(path.join(__dirname, 'src')));

app.get('/', (req, res) => {
    /*req.secure ? next() : res.redirect('https://' + req.headers.host + req.url);*/
    res.sendFile(__dirname + '/src/index.html');
    /*res.write("<h1>Prueba</h1>"); */
});

app.post('/', (req, res) => {
    /*req.secure ? next() : res.redirect('https://' + req.headers.host + req.url);*/
    res.sendFile(__dirname + '/src/index.html');
    /*res.write("<h1>Prueba</h1>"); */
});


io.on('connection', (socket) =>{
    socket.on('prueba', (msg) => {
        console.log('message: ', msg);
    });

    socket.on("localstorage_login", function (data) {
        
        users_sessions.push({
            CORREO_SESSION: data.CORREO,
            RFCEMPRESA_SESSION: data.RFCEMPRESA,
            TIMUSERENC_SESSION: data.TIMUSERENC,
            JWT_SESSION: data.jwt
        });
        socket.emit('localstorage_login_error', {
            error: false,
            msj: "EXITO",
            response: {}
        });        
    });

    socket.on("localstorage_update", function (data) {
        RFCEMPRESA_UPD = data.RFCEMPRESA;
        TIMUSERENC_UPD = data.TIMUSERENC;
        JWT_UPD = data.jwt;

        let filter_users = users_sessions.filter(element => element.JWT_SESSION == JWT_UPD && element.TIMUSERENC_SESSION == TIMUSERENC_UPD && element.RFCEMPRESA_SESSION == RFCEMPRESA_UPD);

        if (filter_users.length == 0) {
            console.log("HUBO UN CAMBIO");
            socket.emit('localstorage_error', {
                error: true,
                msj: "Se detectó un cambio en el localstorage o hay más ventanas abiertas",
                response: {}
            });
        }else{
            socket.emit('localstorage_error', {
                error: false,
                msj: "EXITO",
                response: {}
            } );
        }
    });

    socket.on("localstorage_logout", function (data) {
        let index = users_sessions.findIndex( element => element.JWT_SESSION == data.JWT);
        users_sessions.splice(index, 1);

    });
});

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