import { Client } from "../client.js"; class Tourmanent { /** * @param {Client} client */ constructor(client, name = undefined, nb_players = undefined, nb_players_by_game = undefined, level = undefined, started = undefined, finished = undefined, levels = undefined, id = undefined) { /** * @type {Client} */ this.client = client; this.name = name || `${nb_players_by_game}x1, ${nb_players} players`; this.nb_players = nb_players; this.nb_players_by_game = nb_players_by_game; this.level = level; this.started = started; this.finished = finished; this.levels = levels; this.state = this.get_state(); this.id = id this.connected = false; } get_state() { if (this.finished) return "finished"; if (this.started) return "started"; else return "waiting"; } async init(id) { let response = await this.client._get(`/api/tournaments/${id}`); if (response.status === 404) return 1; let response_data = await response.json(); this.name = response_data.name || `${response_data.nb_players_by_game}x1, ${response_data.nb_players} players`; this.nb_players = response_data.nb_players; this.nb_players_by_game = response_data.nb_players_by_game; this.level = response_data.level; this.started = response_data.started; this.finished = response_data.finished; this.levels = response_data.levels; this.id = response_data.id } leave(event) { if (this.connected == false) return this.connected = false; this._socket.close() this.disconnect_func(event); } toggle_participation() { if (!this.connected) return console.log(this.isParticipating); this.isParticipating = !this.isParticipating; console.log(this.isParticipating); this._socket.send(JSON.stringify({participate: this.isParticipating})); } async join(receive_func, disconnect_func) { if (!await this.client.isAuthentificate()) return null; console.log(window.location.protocol); let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/tournaments/${this.id}`; console.log(url); this._socket = new WebSocket(url); this.connected = true; this.isParticipating = false; this.receive_func = receive_func; this.disconnect_func = disconnect_func; this._socket.onmessage = function (event) { const data = JSON.parse(event.data); receive_func(data); }; this._socket.onclose = this.leave.bind(this); } } export { Tourmanent }