import { GameStore } from "./GameStore";
import { BackendGame } from "../../models/Game";

export class GameStoreImpl implements GameStore {
    gameStore: Map<string, BackendGame> = new Map<string, BackendGame>()
    userGameMap: Map<string, string> = new Map<string, string>()

    get(id: string): BackendGame | undefined {
        return this.gameStore.get(id);
    }
    set(id: string, game: BackendGame): void {
        this.gameStore.set(id, game);
    }
    remove(id: string): void {
        this.gameStore.delete(id);
    }

    setGameIdByUser(userId: string, gameId: string): void {
        this.userGameMap.set(userId, gameId)
    }
    getGameIdByUser(userId: string): string | undefined {
        return this.userGameMap.get(userId);
    }
    removeGameIdByPlayer(userId: string): void {
        this.userGameMap.delete(userId);
    }

    setGameByUser(userId: string, game: BackendGame): void {
        this.setGameIdByUser(userId, game.id);
    }
    getGameByUser(userId: string): BackendGame | undefined {
        const gameId = this.getGameIdByUser(userId);
        return gameId && this.gameStore.get(gameId) || undefined;
    }
    removeGameByPlayer(userId: string): void {
        this.removeGameIdByPlayer(userId);
    }

    getSpeactatingGameIdsByUser(userId: string): string[] {
        const speactatingGameIds = [];
        for (const gameId in this.gameStore.keys()) {
            const game = this.gameStore.get(gameId) as BackendGame;
            const isSpectator = game.spectatorIds.find((value) => value === userId);
            isSpectator && speactatingGameIds.push(game.id);
        }
        return speactatingGameIds;
    }
}