import { AExchangeable } from "../AExchangable.js"; import { Client } from "../Client.js"; import { Profile } from "../Profile.js"; class Tourmanent extends AExchangeable { /** * * @param {Client} client * @param {Number} id the id of the tournament */ constructor(client, id) { super(); /** * @type {Number} */ this.id = id; /** * @type {Client} */ this.client = client; /** * @type {Number} */ this.nb_participants; /** * @type {[Profile]} proutman à encore frappé */ this.participantList = [] /** * @type {Boolean} */ this.started; /** * @type {Number} */ this.finished; /** * @type {"finished" | "started" | "waiting"} must be "finished", or "started", or "waiting". Any other return all elements */ this.state; } /** * * @returns {Promise} */ async init() { let response = await this.client._get(`/api/tournaments/${this.id}`); if (response.status !== 200) return response.status; let response_data = await response.json(); this.import(response_data); } leave(event) { if (this.connected == false) return; this.connected = false; this._socket.close(); this.disconnectHandler(event); } /** * @param {Object} data */ async _receiveParticipantUpdate(data) { this.par } async onError(data) { await this.errorHandler(data); } /** * * @param {MessageEvent} event */ onReceive(event) { const data = JSON.parse(event.data); if (data.detail === "error") this.onError(data); else if (["del_participant", "add_participant"].includes(data.detail)) this._receiveParticipantUpdate(data); } /** * Join the tournament Websocket * @param {CallableFunction} errorHandler * @param {CallableFunction} addParticipantHandler called when a participants join the tournament * @param {CallableFunction} delParticipantHandler called when a participants leave the tournament * @param {CallableFunction} disconnectHandler * @param {CallableFunction} goToHandler called when the next game will start * @returns {?} */ async join(participantsUpdateHandler, errorHandler, goToHandler, disconnectHandler) { if (!await this.client.isAuthenticated()) return null; let url = `${window.location.protocol[4] === 's' ? 'wss' : 'ws'}://${window.location.host}/ws/tournaments/${this.id}`; this._socket = new WebSocket(url); this.connected = true; this.isParticipating = false; this.participantsUpdateHandler = participantsUpdateHandler; this.errorHandler = errorHandler; this.disconnectHandler = disconnectHandler; this.goToHandler = goToHandler; this._socket.onmessage = this.onReceive.bind(this); this._socket.onclose = this.leave.bind(this); } } export { Tourmanent };