import { Injectable, Logger, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';

import { GameEntity, FactionEntity, Game_PersonEntity } from './game.entity';
import { GameDTO } from './game.dto';
import { PersonEntity } from '../user/user.entity';

@Injectable()
export class GameService {
  constructor(
    @InjectRepository(GameEntity)
    private gameRepository: Repository<GameEntity>,
    @InjectRepository(FactionEntity)
    private factionRepository: Repository<FactionEntity>,
    @InjectRepository(PersonEntity)
    private personRepository: Repository<PersonEntity>,
    @InjectRepository(Game_PersonEntity)
    private game_PersonRepository: Repository<Game_PersonEntity>,
  ) {}

  // create a new game
  async createNewGame(personId: string, gameData: GameDTO) {
    // checks if a game with the same name exists already
    const { name } = gameData;
    if (await this.gameRepository.findOne({ where: { name } })) {
      throw new HttpException('Game already exists', HttpStatus.BAD_REQUEST);
    }
    // else add the game to the database
    const game = await this.gameRepository.create({
      ...gameData,
      factions: gameData.factions,
    });
    await this.gameRepository.insert(game);
    // get the id of the game created to pass it to factions table
    const gameid = await this.gameRepository.findOne({
      where: { name: gameData.name },
    });

    gameData.factions.map(async faction => {
      let name = await this.factionRepository.create({
        ...faction,
        game: gameid,
      });
      await this.factionRepository.insert(name);
    });
    return 'success';
  }

  // checks the password, creates an entry in GamePerson table with associated role&faction
  async joinGame(person, gameId, json) {
    const user = await this.personRepository.findOne({
      where: { id: person },
    });
    const game = await this.gameRepository.findOne({ where: { id: gameId } });

    const index = game.passwords.indexOf(json.password);

    // create game_Person entry
/*     const gamePerson = await this.game_PersonRepository.create({
      faction,
      gameId,
      person,
    });
    */
    return 'WIP';
  }

  // returns name and id of each game
  async listGames() {
    const games = await this.gameRepository.find({ relations: ['factions'] });
    return games.map(game => {
      return game.gameObject();
    });
  }

  // returns information about a game identified by id
  async returnGameInfo(id: string) {
    const game = await this.gameRepository.findOne({
      where: { id: id },
      relations: ['factions'],
    });
    return game;
  }
}