/**************************************************************
** cspp51037^M
** lab#2
** ReversiClient.java
** Dan Rocco
** 04/28/02
***************************************************************/

import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
import java.util.*;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.NotBoundException;
import java.net.MalformedURLException;
import java.rmi.server.*;

public class ReversiClient1 extends JApplet
                             implements  ActionListener, PlayerInter
{
   private JTextField id;
   private JTextArea display;
   private JPanel boardPanel, panel2, panel3;
   private JButton b1, b2, b3;
   private Square board[][], currentSquare;
   private char s_board[][];
   private DataInputStream input;
   private DataOutputStream output;
   private char myMark;
   private boolean myTurn;
   private int playerID;
   Reversi game;


   Container cp = getContentPane();

   // Set up user-interface and board
   public void init()  
   {
     try {
   //  UnicastRemoteObject.exportObject( (PlayerInter) this );
     UnicastRemoteObject.exportObject( this );                  
     game = (Reversi) Naming.lookup
           ("rmi://localhost:1224/reversi_game/");
      playerID = game.register( (PlayerInter) this);
       if (playerID != -1){
            display.append("connection established, valid player");
            display.append("I'm player " +
                               (playerID == 0 ? 'X' : 'O'));
        }
         else{
             display.append("two people already playing, can only watch");
        }
        myTurn = (playerID == 0 ? true : false);
    

       }
       catch(Exception e)
       {
	       System.out.println(e);
       }
  
      FlowLayout appletLayout = new FlowLayout(FlowLayout.CENTER, 10,10);
	   cp.setLayout(appletLayout);

      boardPanel = new JPanel();
      GridLayout layout1 = new GridLayout( 8, 8, 0, 0 );
      boardPanel.setLayout( layout1 );

      board = new Square[ 8 ][ 8 ];

      cp.add(boardPanel);

      id = new JTextField();
      id.setEditable( false );

      cp.add( id, BorderLayout.NORTH );

      panel2 = new JPanel();
      panel2.add( boardPanel, BorderLayout.NORTH );
      cp.add( panel2, BorderLayout.NORTH );

       for ( int row = 0; row < board.length; row++ )
	        {
	           for ( int col = 0;
	              col < board[ row ].length; col++ ) {
	              board[ row ][ col ] =
	              new Square( ' ', row * 8 + col );
	              board[ row ][ col ].addMouseListener(
	                 new SquareListener(
	                    this, board[ row ][ col ] ) );

	              boardPanel.add( board[ row ][ col ] );
	           }
	        }
             board[ 3 ][ 3 ].setMark('X' );
             board[ 3 ][ 3 ].repaint();
             board[ 3 ][ 4 ].setMark('O' );
             board[ 3 ][ 4 ].repaint();
             board[ 4 ][ 3 ].setMark('O' );
             board[ 4 ][ 3 ].repaint();
             board[ 4 ][ 4 ].setMark('X' );
             board[ 4 ][ 4 ].repaint();


      panel3 = new JPanel();

      b1=new JButton("Concede");
      panel3.add(b1);
      b1.addActionListener(this);


      b2=new JButton("Skip Turn");
      panel3.add(b2);
      b2.addActionListener(this);

      b3=new JButton("New Game");
      panel3.add(b3);
      b3.addActionListener(this);
      cp.setSize(3,30);
      cp.add( panel3, BorderLayout.CENTER );

      display = new JTextArea( 6, 25 );
      display.setEditable( false );
      cp.add( new JScrollPane( display ),
                    BorderLayout.SOUTH);


   }

public void actionPerformed(ActionEvent ae){

	String label = ae.getActionCommand();
        Object source = ae.getSource();

	if(source == this.b1){
	if ( myTurn )
	     myTurn = false;
         }

	if(source == this.b2){
	if ( myTurn )
 		    myTurn = false;
        }
}

   public void otherPlayerMoved(){
        synchronized(this){
            notify();
        }
    }


   public void testit(int loc){
   boolean tested = false;
   try {                                                                 
       tested = game.validMove(loc,playerID);   
       }
       catch ( Exception ie ) {                                             
              ie.printStackTrace();                                               
              display.append("error " + ie + "\n");                               
           }                                                                                               
        if (tested){                                                         
            display.append("tested " + tested  + "\n");                         
            board[ loc/8 ][ loc%8 ].setMark('X' );                            
            board[ loc/8 ][ loc%8 ].repaint();
            try {
            s_board = game.getBoard();
            }
            catch(Exception eo)
            { 
               System.out.println(eo);
            }
            this.drawBoard(s_board);
            myTurn = false;
            display.append("Waiting for apponent to move \n");
            synchronized(this){
		try{
		wait();
                }
                catch(Exception ie)
                {System.out.println(ie);}
            try {
            s_board = game.getBoard();
            }
            catch(Exception eo)
            { 
               System.out.println(eo);
            }
             this.drawBoard(s_board);
            }                                
          }                         
          else
          {
              myTurn = true;
          }                                                                    
}

   public void drawBoard(char[][] s_board){

      for ( int i = 0; i < 8; i++ )
          for (int j = 0; j < 8; j++ ) {
              board[ i ][ j ].setMark(s_board[i][j]);
              board[ i ][ j ].repaint();
      }
}   
   public void sendClickedSquare( int loc )
   {   display.append("Hi in here in click \n");
        boolean tested = false;
      //  myTurn = true;
        display.append("loc " + loc  + "\n");
        testit(loc);
   }

   public void setCurrentSquare( Square s )
   {
      currentSquare = s;
   }
private Reversi Reversigame;
}

// Maintains one square on the board
class Square extends JPanel {
   private char mark;
   private int location;

   public Square( char m, int loc)
   {
      mark = m;
      location = loc;
      setSize ( 30, 30 );

      setVisible(true);
   }

   public Dimension getPreferredSize() {
      return ( new Dimension( 30, 30 ) );
   }

   public Dimension getMinimumSize() {
      return ( getPreferredSize() );
   }

   public void setMark( char c ) { mark = c; }

   public int getSquareLocation() { return location; }

   public void paintComponent( Graphics g )
   {
      g.setColor(Color.blue);
      super.paintComponent( g );
      g.drawRect( 0, 0, 29, 29 );
      g.drawString( String.valueOf( mark ), 11, 20 );

   }
}

class SquareListener extends MouseAdapter {
   private ReversiClient1 applet;
   private Square square;

   public SquareListener( ReversiClient1 t, Square s )
   {
      applet = t;
      square = s;
   }
  public void mouseReleased (MouseEvent e)
  {
	applet.setCurrentSquare(square);
        applet.sendClickedSquare (square.getSquareLocation());
  }

}

















