import OnlineDuelSync from './online-duel-sync';

export default function GamesManager(ioServer, mariadbConn) {
  let currentGames = new Map();

  // Method to add player into a game, create or add to game syncer
  let addPlayerInGame = function(player, gameId, joinCreatedGame) {
    if (currentGames.has(gameId)) {
      player.isPlayingGameId = gameId;
      return currentGames.get(gameId).addPlayer(player);
    } else if (joinCreatedGame === false) {
      player.isPlayingGameId = gameId;
      currentGames.set(
        gameId,
        new OnlineDuelSync(ioServer, mariadbConn, gameId, player)
      );
      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()) {
        currentGames.delete(id);
      }
    }

    player.isPlayingGameId = -1;
  };

  return {
    addPlayerInGame,
    playerLeft
  };
}