import {client, navigateTo} from "../../index.js";
import { clear, fill_errors } from "../../utils/formUtils.js";
import AbstractAuthentifiedView from "../abstracts/AbstractAuthentifiedView.js";

export default class extends AbstractAuthentifiedView
{
    constructor(params)
	{
        super(params, "Create tournament");
		this.id = params.id;
    }

	async create()
	{
		let name = document.getElementById("name-input").value;
		let nb_players = document.getElementById("nb_players-input").value;
		let nb_players_by_game = document.getElementById("nb_players_by_game-input").value

		let response_data = await client.tournaments.createTournament(nb_players, nb_players_by_game, name);

		if (response_data === null)
			return;

		let id = response_data["id"] 
		if (id !== undefined)
		{
			navigateTo(`/tournaments/${id}`);
			return;
		}

		clear("innerHTML", ["name", "nb_players", "nb_players_by_game"]);
		fill_errors(response_data, "innerHTML");
	}

	async postInit()
	{
		document.getElementById("create-button").onclick = this.create;
	}

	async getHtml()
	{
		return `
			<input type="text" id="name-input" placeholder="Tournament name">
			<span id="name"></span>
			<input type="number" id="nb_players-input" placeholder="Number of players in tournament">
			<span id="nb_players"></span>
			<input type="number" id="nb_players_by_game-input" placeholder="Number of players by game">
			<span id="nb_players_by_game"></span>
			<input type="button" id="create-button" value="Create tournament">
		`
	}
}
