let Users = require('../database').Repositories.Users; let io = require('./sockets.js'); const debug = (d) => { console.log(d); } class Queue { constructor(namespace) { this.matches= []; this._namespace_name = namespace; this.namespace = io; } getName() { return this._namespace_name; } createMatch(Match) { // sockets this.matches.push(match); // create Garbage collector } queue(socket) { // add socket to this queue debug("Joining queue : " + this._namespace_name); socket.join(this._namespace_name + 'queue'); this._matchmaking(); } _matchmaking() { return this.namespace.in(this._namespace_name + 'queue').clients((err, clients) => { this.namespace.emit(this._namespace_name + 'Size', clients.length); return this._checkClients(err, clients); }); } _checkClients(err, clients) { if(err) throw err; if(clients.length < 2) return false; let client1 = clients[0]; let client2 = clients[1]; let socket1 = this.namespace.sockets.connected[client1]; let socket2 = this.namespace.sockets.connected[client2]; let token1 = socket1.request._query['token']; let token2 = socket2.request._query['token']; let channel = 'DQ' + client1 + client2 + this._namespace_name; // abstract joinGame depending on type // to be overriden let matchInfo = this.joinGame(token1, token2, channel); // save User info to DB this._saveUser(token1, matchInfo.playerOneState).then(() => this._saveUser(token2, matchInfo.playerTwoState)) .then (() => this._match(socket1, socket2, channel, matchInfo)) .catch(this._breakMatch); } _saveUser(token, currentGame) { return Users.getUser(token).then((user) => { user.currentGame = currentGame; Users.save(user); }); } _breakMatch(err) { console.log(err); return ; } _match(s1, s2, channel, matchInfo) { // Check queue to make matchmaking s1.leave(this._namespace_name + 'queue'); s2.leave(this._namespace_name + 'queue'); s1.emit('joinGame', { personal: matchInfo.playerOneState, setup: matchInfo.setup}); s2.emit('joinGame', { personal: matchInfo.playerTwoState, setup: matchInfo.setup}); // finish my job! if(this.onMatchFound) this.onMatchFound(s1,s2,channel, matchInfo); } joinGame(token1, token2, channel) { return { channel }; } _updateLobby() { this.namespace.in(this._namespace_name + 'queue').clients((err, clients) => { this.namespace.emit(this._namespace_name + 'Size', clients.length); }); } } module.exports = Queue;