import {client, lang, navigateTo} from "../../index.js";
import { clearIds, fill_errors } from "../../utils/formUtils.js";
import AbstractAuthenticatedView from "../abstracts/AbstractAuthenticatedView.js";

export default class extends AbstractAuthenticatedView
{
    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 = await client.tournaments.createTournament(nb_players, nb_players_by_game, name);
		let response_data = await response.json();

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

		clearIds("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 /* HTML */ `
			<div class='container-fluid'>
				<div class='border border-2 rounded bg-light-subtle mx-auto p-2 col-md-7 col-lg-4'>
					<h4 class='text-center fw-semibold mb-4' id="title">${lang.get("TournamentCreateTitle")}</h4>
					<div class='form-floating mb-2'>
						<input type='text' class='form-control' id='name-input' placeholder='${lang.get("TournamentCreateTournamentName")}'>
						<label for='name-input' id='name-label'>${lang.get("TournamentCreateTournamentName")}</label>
						<span class='text-danger' id='name'></span>
					</div>
					<div class='form-floating mb-2'>
						<input type='number' class='form-control' min='2' max='4' value='2' id='nb-players-by-game-input' placeholder='${lang.get("TournamentCreateNbPlayerByGame")}'>
						<label for='nb-players-by-game-input' id='nb-players-by-game-label'>${lang.get("TournamentCreateNbPlayerByGame")}</label>
						<span class='text-danger' id='nb_players_by_game'></span>
					</div>
					<div class='form-floating mb-2'>
						<input type='number' class='form-control' min='2' value='4' id='nb-players-input' placeholder='${lang.get("TournamentCreateNbPlayer")}'>
						<label for='nb-players-input' id='nb-players-label'>${lang.get("TournamentCreateNbPlayer")}</label>
						<span class='text-danger' id='nb_players'></span>
					</div>
					<div class='d-flex'>
						<button type='button' class='btn btn-primary mt-3 mb-2 mx-2' id='create-button'>${lang.get("TournamentCreateButton")}</button>
						<span class='text-danger my-auto mx-2' id='detail'></span>
					</div>
				</div>
			</div>
		`;
	}
}
