import { Game } from '../domain/Game';
import { GameType } from '../domain/enums/GameType';
import { GameRepository } from '../domain/interfaces/GameRepository';
import { GameFactory } from './GameFactory';
import { Player } from '../domain/entities/Player';
import { RuleFactory } from './RuleFactory';
import { GameStatus } from '../domain/enums/GameStatus';
import { v4 as uuidv4 } from 'uuid';

export class GameService {
    constructor(
        private gameFactory: GameFactory,
        private gameRepository: GameRepository,
        private ruleFactory: RuleFactory
    ) {}

    async createGame(gameType: GameType, initialCondition: string): Promise<Game> {
        return await this.gameFactory.createGame(gameType, initialCondition);
    }

    async getPreparingGames(): Promise<Game[]> {
        const games = await this.gameRepository.findAll();
        return games.filter(game => game.getStatus() === GameStatus.PREPARING);
    }

    async getNotFinishedGames(): Promise<Game[]> {
        const games = await this.gameRepository.findAll();
        return games.filter(game => game.getStatus() !== GameStatus.FINISHED);
    } 

    async getFinishedGames(): Promise<Game[]> {
        const games = await this.gameRepository.findAll();
        return games.filter(game => game.getStatus() === GameStatus.FINISHED);
    }

    async joinGame(gameId: string, playerName: string): Promise<Game> {
        const game = await this.gameRepository.findById(gameId);
        if (!game) {
            throw new Error('游戏不存在');
        }
        if (game.getStatus() !== GameStatus.PREPARING) {
            throw new Error('游戏已经开始或结束，不能加入');
        }

        const player = new Player(uuidv4(), playerName);
        game.addPlayer(player);
        await this.gameRepository.update(game);
        return game;
    }

    async startGame(gameId: string): Promise<Game> {
        const game = await this.gameRepository.findById(gameId);
        if (!game) {
            throw new Error('游戏不存在');
        }
        if (game.getStatus() !== GameStatus.PREPARING) {
            throw new Error('游戏已经开始或结束');
        }

        game.startGame();
        await this.gameRepository.update(game);
        return game;
    }

    async submitAnswer(gameId: string, answer: string): Promise<boolean> {
        const game = await this.gameRepository.findById(gameId);
        if (!game) {
            throw new Error('游戏不存在');
        }

        const rule = this.ruleFactory.createRule(game.getGameType());
        const isValid = await game.submitAnswer(answer, rule);
        await this.gameRepository.update(game);
        return isValid;
    }

    async getGame(gameId: string): Promise<Game> {
        const game = await this.gameRepository.findById(gameId);
        if (!game) {
            throw new Error('游戏不存在');
        }
        return game;
    }
} 