'use strict'; import OnlineDuelSync from './online-duel-sync'; const fs = require('fs'); const path = require('path'); export default function GamesManager(ioServer, mariadbConn) { let currentGames = new Map(); // We create Heroes data from JSON file, it will be needed by the duelController // DuelController has no dependency to browser env nor node env. So it cannot read the // file itself (not same mechanism, in node we use fs readFileSync) // Read once here for all the games to come let allHeroesJson = JSON.parse( fs.readFileSync( path.resolve(__dirname, '../client-server-shared/all-heroes.json') ) ); // Method to add player into a game, create or add to game syncer let addPlayerInGame = function( player, gameId, joinCreatedGame, isNewGame = false, gameOptions = {} ) { if (currentGames.has(gameId)) { player.isPlayingGameId = gameId; let duelSync = currentGames.get(gameId); return duelSync.addPlayer(player); } else if (joinCreatedGame === false) { player.isPlayingGameId = gameId; currentGames.set( gameId, new OnlineDuelSync( ioServer, mariadbConn, gameId, player, isNewGame, gameOptions, allHeroesJson ) ); return true; // We are supposed to join a new game, but not there, must have been deleted in the meantime } else { console.log( 'error : ' + player.playerName + ' tries to join a created game that does not exist anymore' ); return false; } }; let playerLeft = function(player, disconnected) { let id = player.isPlayingGameId; if (currentGames.has(id)) { currentGames.get(id).playerLeft(player, disconnected); if (!currentGames.get(id).hasPlayers()) { // If it was new created game, don't set it to pause, game will be removed if (!currentGames.get(id).isNewlyCreatedGame()) { mariadbConn.updateGameStatus(id, 'PAUSED'); } currentGames.delete(id); } } player.isPlayingGameId = -1; }; return { addPlayerInGame, playerLeft }; }