42_ft_transcendence/frontend/static/js/api/tournament/Tournament.js

147 lines
3.1 KiB
JavaScript

import { Client } from "../Client.js";
class Tourmanent
{
/**
*
* @param {Client} client
* @param {Number} id the id of the tournament
* @param {Number} name
* @param {Number} nb_players
* @param {Number} nb_players_by_game
* @param {Number} level
* @param {Boolean} started
* @param {Boolean} finished
* @param {[]} levels
* @param {String} state
*/
constructor(client, id, name = undefined, nb_players = undefined, nb_players_by_game = undefined, level = undefined, started = undefined, finished = undefined, levels = undefined, state = undefined)
{
/**
* @type {Client}
*/
this.client = client;
/**
* @type {String} the name of the tournament
*/
this.name = name || `${nb_players_by_game}x1, ${nb_players} players`;
/**
* @type {Number}
*/
this.nb_players = nb_players;
/**
* @type {Number}
*/
this.nb_players_by_game = nb_players_by_game;
/**
* @type {Number}
*/
this.level = level;
/**
* @type {Number}
*/
this.started = started;
/**
* @type {Number}
*/
this.finished = finished;
/**
* @type {[]}
*/
this.levels = levels;
/**
* @type {String} must be "finished", or "started", or "waiting". Any other return all elements
*/
this.state = state;
/**
* @type {Number}
*/
this.id = id;
/**
* @type {Boolean} if a websocket connection is enabled
*/
this.connected = false;
}
/**
*
* @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.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.state = response_data.state;
}
leave(event)
{
if (this.connected == false)
return;
this.connected = false;
this._socket.close();
this.disconnect_func(event);
}
toggle_participation()
{
if (!this.connected)
return;
this._socket.send(JSON.stringify({participate: ""}));
}
/**
* Join the tournament Websocket
* @param {CallableFunction} receive_func
* @param {CallableFunction} disconnect_func
* @returns {?}
*/
async join(receive_func, disconnect_func)
{
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.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 };