import _ from 'underscore';

export default class MatchI {
	constructor(socket, game, session) {
		this.game = game;
		this._socket = socket;
		this._session = session;
		this.user = session.username;
		this.player1 = null;
		this.player2 = null;
		this.props = {};
		this.turn = false;

		socket.onmatchpresence = (matchdata) => {
			console.log(matchdata);
			// for player1 client when player2 joins match
			if (this.player2 === matchdata.joins[0].username) {
				//TO Do additional players
				if (this.user == this.player1) {
					game.freezedInput = false;
				} else if (this.user == this.player2) {
					game.freezedInput = true;
				}
				game.log('Received match presence update:', matchdata.joins[0].username);
				game.log(this.player1 + ' turn');
			}

			// player 1 join
			if (this.player1 === matchdata.joins[0].username) {
				if (this.user == this.player1) {
					game.freezedInput = false;
				}
				console.info('Received match presence update:', matchdata.joins[0].username);
			}
		};

		socket.onmatchdata = (matchdata) => {
			console.info('Received match data: %o', matchdata);
			if (matchdata) {
			}
		};
	}

	async matchCreate(s, c) {
		let nm = await this._socket.send({ match_create: {} });
		this.player1 = this._session.username;
		this.props = nm;
		return nm;
	}
	async matchJoin(s, c) {
		let nj;

		var matchList = await c.listMatches(s);
		console.log(matchList);
		var openMatch = _.findWhere(matchList.matches, { size: 1 });

		if (openMatch) {
			nj = await this._socket.send({ match_join: { match_id: openMatch.match_id } });
			console.log(`joined match ${openMatch.match_id}`, nj);
			this.props = nj;
			this.player2 = this._session.username;
			return nj;
		}
	}

	sendMatchData(obj) {
		this._socket.send({ match_data_send: obj });
	}
}

@@ -113,25 +113,24 @@
 ame;%0A%09%09this.
-_
 socket = soc
@@ -137,25 +137,24 @@
 ket;%0A%09%09this.
-_
 session = se
@@ -1171,33 +1171,32 @@
 nm = await this.
-_
 socket.send(%7B ma
@@ -1228,33 +1228,32 @@
 .player1 = this.
-_
 session.username
@@ -1277,19 +1277,38 @@
 nm;%0A
-%09%09
+    
 return 
+Promise.resolve(
 nm
+)
 ;%0A%09%7D
@@ -1343,16 +1343,57 @@
 let nj;%0A
+    this.player2 = this.session.username;
 %0A%09%09var m
@@ -1431,34 +1431,8 @@
 s);%0A
-%09%09console.log(matchList);%0A
 %09%09va
@@ -1525,25 +1525,24 @@
  await this.
-_
 socket.send(
@@ -1693,17 +1693,16 @@
  = this.
-_
 session.
@@ -1715,20 +1715,40 @@
 me;%0A
-%09%09%09
+      
 return 
+Promise.resolve(
 nj
+)
 ;%0A%09%09

clean up match join