RoomManager.ts 1.07 KB
import { Connection } from "../connection/Connection";
import { RoomListMessage } from "../message/types";
import { Room } from "./Room";
import { RoomData } from "./types";

export class RoomManager {
  private static _instance: RoomManager;

  private rooms: Map<string, Room>;

  constructor() {
    RoomManager._instance = this;
    this.rooms = new Map<string, Room>();
  }

  public static instance(): RoomManager {
    return RoomManager._instance;
  }

  public create(name: string, maxConnections: number): Room {
    const room = new Room(name, maxConnections);
    this.rooms.set(name, room);
    return room;
  }

  public get(uuid: string): Room | undefined {
    return this.rooms.get(uuid);
  }

  public delete(uuid: string): void {
    const room = this.get(uuid);
    if (room !== undefined) {
      room.close();
      this.rooms.delete(uuid);
    }
  }

  public sendList(connection: Connection): void {
    var roomData: RoomData[] = [];
    this.rooms.forEach((room) => {
      roomData.push(room.getData());
    });

    connection.send(new RoomListMessage(roomData));
  }
}