const express = require('express');
const app = express();

var http = require('http');

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.end('Servidor Web Socket \n');
});

var io = require('socket.io')(server);
var localstorage_session =  "";

var RFCEMPRESA_SESSION = ""
var TIMUSERENC_SESSION = ""
var JWT_SESSION = ""

var RFCEMPRESA_UPD = ""
var TIMUSERENC_UPD = ""
var JWT_UPD = ""

io.on('connection', function(socket){
  console.log("Usuario conectado");
  socket.emit('test event', 'here is some data ' );
    
  socket.on("localstorage_login", function (data) {
    RFCEMPRESA_SESSION = data.RFCEMPRESA;
    TIMUSERENC_SESSION = data.TIMUSERENC;
    JWT_SESSION  = data.jwt;
    console.log("SESIÓN INICIADA");
  });

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

    if(RFCEMPRESA_SESSION != RFCEMPRESA_UPD || TIMUSERENC_SESSION != TIMUSERENC_UPD ||  JWT_SESSION != JWT_UPD){
      console.log("HUBO UN CAMBIO");
      socket.emit('localstorage_error', {
        error: true,
        msj: "HUBO UNA MODIFICACIÓN EN EL LOCALSTORAGE, USUARIO BLOQUEADO",
        response: {
          RFCEMPRESA: RFCEMPRESA_SESSION,
          TIMUSERENC: TIMUSERENC_SESSION,
          JWT: JWT_SESSION
        }
      });
    }else{
      socket.emit('localstorage_error', {
        error: false,
        msj: "EXITO",
        response: {}
      });
    }
  });

  socket.on("localstorage_logout", function (data) {
    console.log("SESIÓN CERRADA");

    RFCEMPRESA_SESSION = "";
    TIMUSERENC_SESSION = "";
    JWT_SESSION  = data.jwt;

    RFCEMPRESA_UPD = "";
    TIMUSERENC_UPD = "";
    JWT_UPD = "";
  });
});

server.listen(4444, () => {
  console.log("Socket.io server is listening on port 4444");
});

