const fs = require('fs'); export default function OnlineDuelSync( ioServer, mariadbConnector, gameId, firstPlayer ) { let io = ioServer; let mdb = mariadbConnector; let players = new Map(); players.set(firstPlayer.playerName, firstPlayer); let loadGameData = function() { let gameDetails = {}; try { gameDetails = mdb.getGameById(gameId); } catch (err) { console.log('Error retreiving game : ', err.message); } return gameDetails; }; let chat = function(name, message) { io.to(gameId).emit('message', { from: name, text: message }); }; firstPlayer .getSocket() .join(gameId, () => { chat( firstPlayer.playerName, firstPlayer.playerName + ' has entered the game, waiting for second player...' ); }) .emit('update-game-data', loadGameData().game_data) .on('chat', message => { chat(firstPlayer.playerName, message); }); let addPlayer = function(player) { let res = true; if (players.size === 1) { if (players.has(player.playerName)) { console.log( 'ERROR : this player is already there ! ', player.playerName ); return false; } players.set(player.playerName, player); player .getSocket() .join(gameId, () => { chat(player.playerName, player.playerName + ' has entered the game'); }) .emit('update-game-data', loadGameData().game_data) .on('chat', message => { chat(player.playerName, message); }); } else { console.log( 'Already 2 players, weird :' + player.playerName + ' was trying to join : ', players ); res = false; } return res; }; let playerLeft = function(player, disconnected) { let playerLeaving = players.get(player.playerName); if (playerLeaving) { if (!disconnected) { playerLeaving.getSocket().leave(gameId); } chat(player.playerName, player.playerName + ' has left the game'); players.delete(player.playerName); } }; let hasPlayers = function() { return players.size > 0; }; return { addPlayer, playerLeft, hasPlayers }; }