var Komachan = require('./komachan');

function KomachanHandler() {
  var self = this;
  self.color;
  self.komachan = new Komachan();
  self.socket = require('./socket').socket().socket;
  self.moved();
  self.socket.on('win', function(mes){
    console.log(mes);
  });
  self.socket.on('lose', function(mes) {
    console.log(mes);
  });
  self.socket.on('err', function(err){
    console.log(err);
  });
}

KomachanHandler.prototype.start = function() {
  var self = this;
  self.socket.emit('new-game', {});
  self.socket.on('confirm', function(game) {
    self.socket.emit('agree', game);
  });
  self.socket.on('start', function(game) {
    console.log(game);
    if (game.header.firstMove === 'client') {
      self.color = 0;
      self.move();
    } else {
      self.color = 1;
    }
  });
}

KomachanHandler.prototype.move = function() {
  var self = this;
  self.komachan.search(function(err, move){
    if(err) {
      console.log(err);
      self.finish();
      return;
    }
    self.socket.emit('move', move);
  });
}

KomachanHandler.prototype.moved = function() {
  var self = this;
  self.socket.on('moved', function(move){
    console.log('moved', move);
    //if (move.lose) { return console.log('You are lose.')}
    if (move.color !== self.color){
      self.komachan.move(move, function(err, moved) {
        if (err) { return console.log(err); }
        self.move();
      });
    }
  });
}

KomachanHandler.prototype.end = function() {
  this.komachan.end();
}

KomachanHandler.prototype.finish = function(listener) {
  this.socket.on('win', listener);
  this.socket.on('lose', listener);
}

module.exports = KomachanHandler;

@@ -22,17 +22,18 @@
 e('.
-/komachan
+./index.js
 ');%0A
@@ -117,12 +117,20 @@
 n = 
+Komachan.
 new
- 
 Koma
@@ -202,24 +202,49 @@
 lf.moved();%0A
+  self.komachan.start();%0A
   self.socke
@@ -892,24 +892,36 @@
 lf = this;%0A 
+ var kmove =
  self.komach
@@ -934,69 +934,27 @@
 rch(
-function(err, move)%7B%0A    if(err) %7B%0A      console.log(err);%0A  
+);%0A  if (!kmove) %7B%0A
     
@@ -972,18 +972,16 @@
 ();%0A    
-  
 return;%0A
@@ -982,22 +982,18 @@
 turn;%0A  
-  %7D%0A  
+%7D%0A
   self.s
@@ -1015,21 +1015,16 @@
 e', 
+k
 move);%0A
-  %7D);%0A
 %7D%0A%0AK
@@ -1130,24 +1130,26 @@
 (move)%7B%0A    
+//
 console.log(
@@ -1168,68 +1168,8 @@
 e);%0A
-    //if (move.lose) %7B return console.log('You are lose.')%7D%0A
     
@@ -1233,83 +1233,36 @@
 move
-, function(err, moved) %7B%0A        if (err) %7B return console.log(err); %7D
+);%0A      self.move();
 %0A    
+%7D%0A
     
@@ -1270,31 +1270,25 @@
 elf.
-move();%0A      %7D);%0A    %7D
+komachan.print();
 %0A  %7D
@@ -1336,24 +1336,26 @@
 ction() %7B%0A  
+//
 this.komacha

update KomachanHandler to node