import java.net.*;
import java.io.*;
import java.util.*;
/**
 *  This class allows the checker game to be played over
 *  a network.  This class extends Player class
 *  @vesion 4.0
 *  
 */
class NetPlayer extends Player 
{
   private Scanner in;
   private PrintWriter out;
   private static int port = 4444;
   private ServerSocket serverSocket;
   private Socket clientSocket;

   /**
     *  Constructor for the server socket  This method throws
     *  an IOException
     *  @param pNum      int for the player number
     *  @param dir       int direction of play
     *  @param n         String string for name
     *  @param boardRef  Board this is a reference to the Board Class
     *  
    */
   // Server Socket
   public NetPlayer (int pNum, int dir, String n, Board boardRef) throws IOException
   {
      super(pNum, dir, n, boardRef);
      serverSocket = new ServerSocket (port);
      clientSocket = serverSocket.accept();

      // use the InputStream object to create a Scanner.
      in = new Scanner (clientSocket.getInputStream());

      // use the OutputStream object to create a PrintWriter
      out = new PrintWriter (clientSocket.getOutputStream(), true);
   }

   /**
     *  Constructor for the Client socket.  This method throws an
     *  IOException
     *  @param  pNum         int for the player number
     *  @param  dir          int direction
     *  @param  n            String for name
     *  @param  server       String for server
     *  @param  boardRef     Board this is a reference to the Board Class
    */ 
   // Client Socket
   public NetPlayer (int pNum, int dir, String n, String server, Board boardRef) throws 
                     UnknownHostException, IOException
   {
      super(pNum, dir, n, boardRef);
      clientSocket = new Socket(server, port);

      // use the InputStream object to create a Scanner.
      in = new Scanner (clientSocket.getInputStream());

      // use the OutputStream object to create a PrintWriter
      out = new PrintWriter (clientSocket.getOutputStream(), true);
   }
   
   /**
     *  This methods sends the name of a player
     *  @param n      String  that represents a name
    */
   public void sendMyName(String n)
   {
      out.println(n);
   }
   
   /**
     *  This method is an accessor of the opponents name
     *  @return  String
    */
   public String getOpponentName()
   {
      return in.nextLine().intern();
   }
   /**
     *  This method returns the interger 1 for NetPlayer
     *  @return  int    the interger 1 represents NetPlayer
    */
   public int playerType()
   {
      return 1;
   }

   /**
     *  This method ends the turn this player and sets the 
     *  opponents turn
     *  @return  int 
     *
    */
   public int endTurn()
   {
      this.isMyTurn = false;
      return this.opponent.setTurn();
   }
   /**
     *  This method sets the turn of the appropriate player
     *  @return  int    this is for the player number
    */
   public int setTurn()
   {
      this.isMyTurn = true;
      out.println("end");
      return this.getPlayerNumber();
   }
   
   /**
     *  This method sends the coordinates for the current move
     *  @param  col1   column
     *  @param  row1   row
     *  @param  col2   column
     *  @param  row2   row
    */
   public void sendMove(int col1, int row1, int col2, int row2, 
                        String spMove)
   {
      if(spMove.intern() == "Castling" && 
         this.b.sq[col2][row2].contents.pieceType() == "King")
      {
         b.moveLog.add((b.moveLog.size() - 1), this.opponent.name + " " + 
                        this.b.sq[col1][row1].contents.pieceType() + " " +
                        col1 + " " + row1 + " " + col2 + " " + row2 + " " +
                        spMove);
      }
      else
      {
         b.moveLog.addElement(this.opponent.name + " " + 
                              this.b.sq[col1][row1].contents.pieceType() + " " +
                              col1 + " " + row1 + " " + col2 + " " + row2 + " " +
                              spMove);
      }

      System.out.println(b.moveLog.get(b.moveLog.size()-1));      
      out.println((7 - col1) + " " + (7 - row1) + " " + 
                  (7 - col2) + " " + (7 - row2) + " " + 
                  spMove);
   }
   /**
     *  This method parses coordinates that are sent.
     *  @param b   reference to the board 
    */
   public synchronized void waitForTurn(Board b)
   {
      String commandGetter = "";
      String tokens[];
      int commandsGotten = 0, col1, row1, col2, row2, pcNo, pcID;
      String spMove;
      Piece tempPiece;
      
      while (commandGetter != "end")
      {
         b.repaint();
         if (in.hasNextLine())
         {
            commandGetter = (in.nextLine()).intern();
            commandsGotten++;
            
            if (commandGetter == "end" && commandsGotten == 1)
            {
               hasWon = true;
               b.gameOver = true;
            }
            
            if (commandGetter != "end")
            {
               tokens = commandGetter.split(" ");
               
               col1 = new Integer(tokens[0]);
               row1 = new Integer(tokens[1]);
               col2 = new Integer(tokens[2]);
               row2 = new Integer(tokens[3]);
               spMove = (tokens.length > 4) ? tokens[4] : "";
               pcNo = b.sq[col1][row1].contents.getPieceNumber();
               pcID = b.sq[col1][row1].contents.pieceTypeID();
               specialMove = spMove;

/*               System.out.println(this.name + " " + b.sq[col1][row1].contents.pieceType() + '\n' +
                                  col1 + ", " + row1 + '\n' +
                                  col2 + ", " + row2 + '\n' +
                                  checkCaused + " " + spMove + '\n' +
                                  this.getPlayerNumber() + " " + pcNo + '\n' + pcID); */
               
      switch (pcID)
      {
         case 1:
            tempPiece = new Pawn(col1 * b.width,
                                 row1 * b.width,
                                 b.width,
                                 color,
                                 this,
                                 pcNo, b.set);
            break;
         case 2:
            tempPiece = new Knight(col1 * b.width,
                                   row1 * b.width,
                                   b.width,
                                   color,
                                   this,
                                   pcNo, b.set);
            break;
         case 3:
            tempPiece = new Bishop(col1 * b.width,
                                   row1 * b.width,
                                   b.width,
                                   color,
                                   this,
                                   pcNo, b.set);
            break;
         case 4:
            tempPiece = new Rook(col1 * b.width,
                                 row1 * b.width,
                                 b.width,
                                 color,
                                 this,
                                 pcNo, b.set);
            break;
         case 5:
            tempPiece = new Queen(col1 * b.width,
                                  row1 * b.width,
                                  b.width,
                                  color,
                                  this,
                                  pcNo, b.set);
            break;
         case 6:
            tempPiece = new King(col1 * b.width,
                                 row1 * b.width,
                                 b.width,
                                 color,
                                 this,
                                 pcNo, b.set);
            myKing = (King) tempPiece;
            break;
         default:
            tempPiece = new Pawn();
      }
      
      if(spMove.intern() == "PromotionB"){tempPiece = new Bishop(tempPiece);}

      if(spMove.intern() == "PromotionK"){tempPiece = new Knight(tempPiece);}

      else if(spMove.intern() == "PromotionR"){tempPiece = new Rook(tempPiece);}

      else if(spMove.intern() == "PromotionQ"){tempPiece = new Queen(tempPiece);}
      
/*               System.out.println(tempPiece.player.name + " " + tempPiece.pieceType() + '\n' +
                                  tempPiece.getCol() + ", " + tempPiece.getRow()); */

               b.moveLog.addElement(this.name + " " + 
                           tempPiece.pieceType() + " " +
                           col1 + " " + row1 + " " + 
                           col2 + " " + row2 + " " +
                           spMove);
               System.out.println(b.moveLog.get(b.moveLog.size()-1));
               tempPiece.executeMove(col2, row2, b, this);
               b.sq[col2][row2].contents = tempPiece;
               
               b.pc[this.getPlayerNumber()][pcNo] = tempPiece;
               this.setPieceArray(b.pc[this.getPlayerNumber()]);

               if (spMove.intern() == "EnPassant")
               {
                  b.sq[col2][row2-this.direction].
                      contents.hasBeenTaken(b.sq[col2][row2+this.direction]);
               }
               
               b.repaint();
            }
            
            if (commandGetter == "end" && commandsGotten > 1)
            {
               b.currentPlayer = b.players[b.thisPlayer].setTurn();
               b.setLabel();
               b.repaint();
            }
         }
      }
   }
   
   /**
     *  This method is a synchronized method used with threads
     *  
    */
   public synchronized void run()
   {
      sendMyName(this.opponent.name);
      while (!(in.hasNextLine()));
      this.name = getOpponentName();
      this.b.setLabel();
      
      for(;;)
      {
            waitForTurn(b);
      }
   }
}