import { Client } from "../client.js";
import { Tourmanent } from "./tournament.js";

class Tourmanents
{
	/**
	 * @param  {Client} client
	 */
	constructor(client)
	{
		/**
		 * @type {Client}
		 */
		this.client = client
	}

	/**
	 * 
	 * @param {Number} id 
	 * @returns {?Promise<Tournament>}
	 */
	async getTournament(id)
	{
		let tournament = new Tourmanent(this.client);
		if (await tournament.init(id))
			return null;
		return tournament;
	}

	/**
	 * 
	 * @param {Number} nb_players 
	 * @param {Number} nb_players_by_game 
	 * @param {String} name 
	 * @returns 
	 */
	async createTournament(nb_players,  nb_players_by_game, name = "")
	{
		let response = await this.client._post("/api/tournaments/", {nb_players: nb_players, nb_players_by_game: nb_players_by_game, name: name});

		if (response.status !== 200)
			return response.status;

		let response_data = await response.json();
		return response_data;
	}

	/**
	 * @param {String} state must be "finished", or "started", or "waiting". Any other return all elements
	 * @returns {?Promise<[Tourmanent]>}
	 */
	async search(state)
	{
		let response = await this.client._get(`/api/tournaments/search/${state}`);
		let response_data = await response.json()

		if (response.status === 403)
		{
			this.client._update_logged(false);
			return null;
		}

		let tournaments = [];

		response_data.forEach(tournament_data => {
			tournaments.push(new Tourmanent(this.client,
											tournament_data.name,
											tournament_data.nb_players,
											tournament_data.nb_players_by_game,
											tournament_data.level,
											tournament_data.started,
											tournament_data.finished,
											tournament_data.levels,
											tournament_data.id));
		});

		return tournaments;
	}

	/**
	 * Get all tournaments
	 * @returns {?Promise<[Tourmanent]>}
	 */
	async all()
	{
		return await this.search("");
	}
	
}

export { Tourmanents }