import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.NotBoundException;
import java.net.MalformedURLException;
import java.rmi.server.*;

public class Player implements PlayerInter{
    private int playerID;
    private char[][] board;
    private boolean myTurn;
    Reversi game;

    Player() throws Exception{
	System.out.println( "Exporting the client" );
	UnicastRemoteObject.exportObject( (PlayerInter) this );
	game = (Reversi) Naming.lookup
	    ("rmi://localhost:1224/reversi_game");
	playerID = game.register( (PlayerInter) this);
	if (playerID != -1){
	    System.out.println("connection established, valid player");
	    System.out.println("I'm player " +
			       (playerID == 0 ? 'X' : 'O'));
	}
	else{
	    System.out.println("two people already playing, can only watch");
	}
	myTurn = (playerID == 0 ? true : false);
    }

    public void otherPlayerMoved(){
	synchronized(this){
	    notify();
	}
    }

    public void play() throws Exception{
        boolean validMove = false;
	while (true){
	    while (myTurn){
		System.out.print("Enter next move >> ");
                String input = ParserUtils.getKeyInput();                       
                String[] tokens = ParserUtils.getTokens(input);                
                int loc = Integer.parseInt(tokens[0]); 
                validMove = game.validMove(loc,playerID);
                if (validMove){                                               
                   myTurn = false;                                              
                   board = game.getBoard();
	        }
                else {
                  myTurn = true;
                  System.out.println("invalid move try again ");   
                  }    
	         }
		System.out.println("Waiting for opponents move");
		synchronized(this){
		    wait();
		
		board = game.getBoard();
		this.drawBoard(board);
		System.out.print("Enter next move >> ");
	    }
	    String input = ParserUtils.getKeyInput();
	    String[] tokens = ParserUtils.getTokens(input);
	    int loc = Integer.parseInt(tokens[0]);

	    validMove = game.validMove(loc,playerID);
	}
    }

    private void drawBoard(char[][] board){
	for (int i = 0; i < 8; ++i){
	    for (int j = 0; j < 8; ++j){
		System.out.print(board[i][j] + "\t");
	    }
	    System.out.print("\n");
	}
    }



    public static void main(String[] args) throws Exception{
        System.setProperty("java.security.policy", "client.policy");
//        System.setSecurityManager(new RMISecurityManager());
	Player player = new Player();
	player.play();

    }

}






