const User = require("./User.js"); const state = require("./state.js"); /** * * @param {string} socketId * @param {number} lobbyId * @returns {Lobby} */ function joinLobby(socketId, lobbyId) { let lobby = state.getLobby(lobbyId); if (!lobby) { lobby = state.createLobby(lobbyId); } lobby.addUser(new User(socketId)); if (!lobby.hasLeader()) { lobby.setLeader(socketId); } state.lobbies[lobby.name] = lobby; return lobby; } function leaveLobby(socketId) { Object.keys(state.lobbies).forEach(lobbyId => { const lobby = state.getLobby(lobbyId); if (!lobby) { return; } lobby.removeUser(socketId); if (!lobby.hasUsers()) { state.removeLobby(lobbyId); return; } if (lobby.getLeader() === socketId) { lobby.setRandomLeader(); } }); } /** * * @param socketId * @returns {Lobby|undefined} */ function getUserLobby(socketId) { for (let lobbyId of Object.keys(state.lobbies)) { const lobby = state.getLobby(lobbyId); if (!lobby) { continue; } if (lobby.getUser(socketId)) { return lobby; } } return undefined; } module.exports = {joinLobby, leaveLobby, getUserLobby};