
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
// https://socket.io/docs/v4/handling-cors/
const io = new Server(server, {
	cors: {
		// change this for the real front origin
		origin: "*"
	}
});
const send_msg = require('./event_sendmsg');
const add_user = require('./event_adduser');
const create_room = require('./event_createroom');

let usernames = {};
let rooms = [
	{ name: 'room1', id: 1 },
	{ name: 'room2', id: 2 },
	{ name: 'room3', id: 3 }
];
let last_room = 0;

io.on('connection', (socket) => {

	socket.on('adduser', (username) => {
		add_user(socket, username, usernames, rooms);
	});

	socket.on('sendmsg', (msg) => {
		send_msg(socket, msg);
	});

	socket.on('createroom', (room_name) => {
		create_room(room_name);
	});

	socket.on('joinlastroom', () => {
		if (socket.room !== null)
			socket.emit('updaterooms', socket.room);
	});

	socket.on('switchroom', function(newroom){
		// leave the current room (stored in session)
		socket.leave(socket.room);
		// join new room, received as function parameter
		socket.join(newroom);
		socket.emit('updatechat', 'SERVER', 'you have connected to '+ newroom);
		// sent message to OLD room
		socket.broadcast.to(socket.room).emit('updatechat', 'SERVER', socket.username+' has left this room');
		// update socket session room title
		socket.room = newroom;
		socket.broadcast.to(newroom).emit('updatechat', 'SERVER', socket.username+' has joined this room');
	//	socket.emit('updaterooms', rooms, newroom);
	});

	socket.on('disconnect', () => {
		// remove the username from global usernames list
		delete usernames[socket.username];
		// update list of users in chat, client-side
		io.sockets.emit('updateusers', usernames);
		// echo globally that this client has left
		socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
		socket.leave(socket.room);
	});

});

server.listen(3000, function () {
	console.log('server running on 3000');
})

