const MatchService = require('./MatchService.js'); const RandomFreeQueue = require('./queues/RandomFreeQueue.js'); const io = require('./sockets.js'); let Users = require('../database').Repositories.Users; const GameMachine= require('../game').GameMachine; class ThirdPartyServer { constructor() { console.log('TPS'); let randomFreeQueue = new RandomFreeQueue(); randomFreeQueue.onMatchFound = (s1, s2, channel, matchInfo) => { console.log("[TPS]Match Found: " + channel) let match = new MatchService(s1,s2, channel, matchInfo); match.onMatchFinished = () => { console.log("[TPS] -- MATCH FINISHED"); this._dropPlayers(channel); }; this.matches[channel] = match; }; this.queues = [ randomFreeQueue ]; //setup socket // is always called io.on('connection', (socket) => { console.log("Default connection:" + socket.id); // User connected ! // check if user is in game! this.userInGame(socket).then(() => socket.join(socket._user.id)); /////// // Setup Events socket.on('disconnect', this._updateLobby); socket.on('chatMsg', this._chatMsg); // create join queue Events this.queues.forEach((queue) => socket.on('join_' + queue.getName(), () => { return queue.queue(socket); })); this._updateLobby(); }); this.matches = {}; } _dropPlayers(channel) { console.log("Dropping channel: " + channel ); return Users.dropChannel(channel); } _setupSocket(socket, channel) { socket.on('broadcast', (data) => this._broadcast(data, channel)); socket.on('abandon', (data) => this._abandon(data, channel)); socket.on('gameOver', (data) => this._gameOver(data, channel)); socket.on('dispute', (data) => this._dispute(data, channel)); socket.leave('queue', this.errorHandler); socket.join(channel, this.errorHandler); } _updateLobby() { io.clients((err, clients) => { io.emit('lobbySize', clients.length); }); if(this.queues) { this.queues.forEach((queue) => { queue._updateLobby(); }); } } _chatMsg(msg) { msg.time = new Date().toISOString(); let rId = msg.receiverId; if(!rId) { console.log("No receiverID."); return; } io.to(rId).emit('chatMsg'); } // createMatch(Match) { // sockets // this.matches.push(match); // create Garbage collector // } // queue(socket) { // // add socket to this queue // // add Socket to Queues // // Handle all queues // } // match() { // // Check queue to make matchmaking // } userInGame(socket) { let token = socket.request._query['token']; return Users.getUser(token) .then((user) => { socket._user = user; if(user.currentGame !== null && user.currentGame !== undefined) { if(this.matches[user.currentGame.channel]) { console.log("Game in progress... Sending details...") this.matches[user.currentGame.channel].reconnect(socket, user.currentGame); // send GameID return user; } } return false; }); } } module.exports = ThirdPartyServer;