const player = localStorage.getItem("login");
const gameID = localStorage.getItem("gameID");

var requestIndex
parent.nodeSend(player, 'Hello');

function invite(contestant) {
	parent.nodeSend(player, 'Request to play', contestant);
	requestIndex++
}

function deny(contestant) {
	parent.nodeSend(player, 'Request denied', contestant);
}
function accept(contestant) {
	parent.nodeSend(player, 'Request accepted', contestant);
}

function messageProcessing(event) {
	console.log(`> Réception données: ${event.data}`);
	if(isJsonString(event.data)) {
		//console.log(' ... Message JSON valide');
		const message = JSON.parse(event.data);
		const sender = message.from.toLowerCase();
		if(sender=='node') {
			const notification = message.notif;
			switch(notification.toLowerCase()) {
				case 'players online':
					if(message.data!='none') {
						message.data.forEach((player) => {
							addLine('players', player.login, player);
						})
					}
					break;
				case 'add player':
					var player = message.data;
					if(player.login) addLine('players', player.login, player);
					if(player.status=='in game' && player.gameID==gameID) navGameBoard();
					break;
				case 'remove player':
					var player = message.data;
					if(player.login) removeLine('players', player.login);
					break;
				case 'update player':
					var player = message.data;
					updateLine('players', player.login, player);
					break;
				case 'requested to play':
					updateLine('players', message.data, {'status':'requested to play'});
					setTimeout(() => {deny(message.data);}, 60000);
					break;
				case 'request rejected':
					requestIndex--
					break;
				case 'resume game':
					break;
				case 'game ready':
					localStorage.setItem("gameID", message.data);
					navGameBoard();
					break;
				default:
					unknownMessage  = `!!! Réception d'un message inconnu)\n`;
					unknownMessage += ` Notification : ${notification}\n`;
					if(message.data) unknownMessage += ` Données : ${JSON.stringify(message.data)}`;
					console.error(unknownMessage);
			}
		}
	} else {
		console.error(`Message "${event.data}" non traité`);
	}
}