import javax.swing.*;
import java.awt.*;
import java.awt.GradientPaint;
import java.awt.event.*;
import java.util.Vector;
/**
 *  This class creates a Frame by extending JPanel.
 *  A Checker Board is created in the panel.
 *  public
 *  @author Casey Daughtery, Joshua Canter, Yvon Feaster 
 *  @version 2.0
*/
                                                                             
public class Board extends JPanel implements ComponentListener, ActionListener 
{
   protected Square sq[][];//space for a reference to 2D array of Square
   protected Piece ch[][];
   protected Board boardRef;
   protected int width;
   protected Piece draggedPiece;
   protected Player players[];
   protected int currentPlayer;
   protected boolean playerIsMidJump;
   protected static boolean notReady = true;
   protected JLabel status1, status2, status3;
   protected Color p1c, p1s, p2c, p2s;
   protected JFrame frame;
   /**
    *  This is the constructor.  
    *  
    * 
   */
   public Board()
   {
      JFrame frame = new JFrame("Phase 2-CPSC 215");
      frame.setSize (504,569);
      frame.add(this);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setVisible(true);
      this.frame = frame;
      sq = new Square[8][8]; //space for 64 references to squares
      ch = new Piece[2][12];
      players = new Player[2];
      draggedPiece = new Pawn ();
      addMouseListener (new DemoAdapter());
      addMouseMotionListener (new DemoAdapter());
      addComponentListener (this);
      setupMenu(frame);
      setupLabel(frame);

      playerIsMidJump = false;
      width = (this.getSize().height < this.getSize().width) ?
                         this.getSize().height / 8 : this.getSize().width / 8; 
                               repaint();
   }//end constructor
   
   /**
    *  This method sets up the board (8 X 8) with all the squares.
    *  It sets the color of each square, determines if the square is 
    *  able to receive a Piece, sets up an array of 12 pawns per Player
    *  and informs the square of its Pawn
    *  public
    *
   */
   public void setUpBoard()
   {
     int redcount = 0;
     int blkcount = 0;
     
     players[0] = new Player(0);
     players[1] = players[0].opponent;
     status1.setText("It is now " + players[currentPlayer].name + 
                        "'s turn.");
     
     for(int row = 0; row < 8; row++)
     {
         for(int col = 0; col < 8; col++)
         {           
            sq[col][row] = new Square(col, row, width);  //creates 64 squares
            
            if ( (row % 2) == (col % 2) )
            {
                sq[col][row].color = new Color(181, 164, 254);
            }
            else
            {
               sq[col][row].color = new Color(19, 1, 95);
            }            
            
	          if (sq[col][row].isOccupiable && row < 3)
 	          {
 	             ch[1][redcount] = new Pawn(col * width + (width * 5 / 90), 
 	                                    row * width + (width * 5 / 90), 
 	                                    (width-(width * 1 / 9)), 
 	                                    Color.red, players[1], redcount);
               sq[col][row].hasChecker = true;
               sq[col][row].contents = ch[1][redcount];
               redcount++;
            }            
            else if(sq[col][row].isOccupiable && row > 4)
            {
 	             ch[0][blkcount] = new Pawn(col * width + (width * 5 / 90), 
 	                                    row * width + (width * 5 / 90), 
 	                                    (width-(width * 1 / 9)), 
 	                                    Color.black, players[0], blkcount);
               sq[col][row].hasChecker = true;
               sq[col][row].contents = ch[0][blkcount];
               blkcount++;
            }          
            else // if((row > 3 && row < 4) || !(sq[col][row].isOccupiable))
            {
               sq[col][row].hasChecker = false;
            }
         }//end row
      }//end col      
      
      players[0].setCheckersArray(ch[0]);
      players[1].setCheckersArray(ch[1]);  
      repaint();    
   }//end constructor  
   
   /** 
    *  This method overrides the JPanel paint method.
    *  Calls each square's drawSquare method
    *  Calls drawChecker on the draggedPiece if there is one. 
    *  public
    *  @param g    uses Graphics passed in 
   */
   public void paint(Graphics g)
   {
      if (notReady)
         return;
      super.paint(g);

      for ( int row = 0;  row < 8;  row++ ) 
      {
         for ( int col = 0;  col < 8;  col++)   
         {
            sq[col][row].drawSquare(g);
         }//end col
      }//end row

      if (!draggedPiece.isNull())
      {
         draggedPiece.drawChecker(g);
      }
   }//end paint
   
   /**
     *  This class is used to reset the board when and
     *  instance of it is invoked.  It extends AbstractAction.
     *  public 
     *   
    */ 
   class resetBoard extends AbstractAction
   {
      /**
        *  Constructor 
       */
      public resetBoard()
      {
      }
      /**
        *  Calls setUpBoard()
        *  @param e      
       */
      public void actionPerformed(ActionEvent e)
      {
         boardRef.sq = new Square[8][8]; //space for 64 references to squares
         boardRef.ch = new Piece[2][12];
         boardRef.players = new Player[2];
         boardRef.draggedPiece = new Pawn ();
         boardRef.currentPlayer = 0;
         boardRef.setUpBoard();

         boardRef.repaint();
      }
   }
   
   /**
     *  This class closes the board when and instance of it 
     *  is called.  It extends AbstractAction
    */
   class closeBoard extends AbstractAction
   {
      /**
        *  Constructor
       */
      public closeBoard()
      {
      }
      
      /**
        *  This method closes the program when called
       */
       
      public void actionPerformed(ActionEvent e)
      {
         System.exit(0);
      }
   }
   
   /**
     *  This method creates the menu on the Frame, sets up the Mnemonics
     *  and set the actions 
     *  @param f   
    */
     
   public void setupMenu(JFrame f)
   {
      
      JMenuItem close, newGame;
      JMenu menu; 
      Action reset, exit;
      JMenuBar jmb = new JMenuBar();
      f.setJMenuBar(jmb);
      menu = new JMenu("File");
      menu.setMnemonic(KeyEvent.VK_F);
      jmb.add(menu);

      reset = new resetBoard();
      exit = new closeBoard();
      newGame = new JMenuItem();
      close = new JMenuItem();
      newGame.setAction(reset);
      newGame.setText("New Game");
      newGame.setMnemonic(KeyEvent.VK_N);
      close.setAction(exit);
      close.setText("Exit");
      close.setMnemonic(KeyEvent.VK_X);
      newGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, 
                             ActionEvent.ALT_MASK));
      close.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, 
                           ActionEvent.ALT_MASK));
      menu.addActionListener(this);
      newGame.addActionListener(this);
      close.addActionListener(this);

      menu.add(newGame);
      menu.addSeparator();
      menu.add(close);      
   }

   /**
     *  Creates a JLabel to display information about Player and turns.
     *  @param f
    */
   public void setupLabel(JFrame f)
   {
      JPanel panel = new JPanel(new GridLayout(2,2, 0, 0));
      
      status1 = new JLabel("Player 1's turn");
      panel.add(status1);
      panel.setVisible(true);
      f.add(status1, BorderLayout.SOUTH);
   }
   
   /**
     *  This method overrides an interface method
     *  @param e
    */      
   public void actionPerformed(ActionEvent e) 
   {
   }
               
   /**
     *  This nested class is to allow the use of the MouseAdapter class
     *  Extends MouseAdapter
     *  public
    */ 
   public class DemoAdapter extends MouseAdapter 
   {
  
     /** 
      *  This method is used to identify the location of the mouse click
      *  in relation to the board in general if there is a Piece at this
      *  location it becomes the draggedPiece
      *  public
      *  @param e
     */
      public void mousePressed(MouseEvent e)
      {
         int row = 0;
         int col = 0;
         col = e.getX() / width;
         row = e.getY() / width;

         if (row > 7 || col > 7)
         {
            return;
         }
         
         if (sq[col][row].contents == null ||
             sq[col][row].contents == null)
         {
            return;
         }

         if (!sq[col][row].contents.isNull())         
         {
            if (sq[col][row].contents.player.playerNumber == currentPlayer)
            {
               draggedPiece = sq[col][row].contents;
            }
         }
         
         if (!draggedPiece.isNull())
         {
            draggedPiece.setXpos(e.getX()-(width * 4 / 9));
            draggedPiece.setYpos(e.getY()-(width * 4 / 9));
            repaint();
         }
      }
      
      /**
       *  This method sets the draggedPiece to follow the mouse and calls
       *  repaint(). 
       *  public
       *  @param e
      */        
      public void mouseDragged(MouseEvent e) 
      {
         int row = 0;
         int col = 0; 
         col = e.getX() / width;
         row = e.getY() / width;
         if (!draggedPiece.isNull())
         {
            draggedPiece.setXpos(e.getX()-(width * 4 / 9));
            draggedPiece.setYpos(e.getY()-(width * 4 / 9));
            repaint();
         }
      }
      /**
       *  This method sets the draggedPiece to follow the mouse and calls
       *  repaint() only if the player is forced to multi-jump. 
       *  public
       *  @param e
      */          
      public void mouseMoved(MouseEvent e) 
      {
         if (playerIsMidJump)
         {
            int row = 0;
            int col = 0; 
            col = e.getX() / width;
            row = e.getY() / width;
            if (!draggedPiece.isNull())
            {
               draggedPiece.setXpos(e.getX()-(width * 4 / 9));
               draggedPiece.setYpos(e.getY()-(width * 4 / 9));
               repaint();
            }
         }
      }
      
      /**
       *  This method determines where the mouse is released.  If the Checker 
       *  is released outside of the board it returns it to the original 
       *  square. It coordinates calls to the methods playerMustJump, moveIsValid
       *  and executeMove.  
       *  public
       *  @param e
      */
      public void mouseReleased(MouseEvent e) 
      {
         boolean mustJump, validMove, doesJump;
         int row = 0; 
         int col = 0;
         col = e.getX() / width;
         row = e.getY() / width;

         if (draggedPiece.isNull())
         {
            repaint();
            return;
         }

         //checks if outside the board
         if (col > 7 || row > 7 || col < 0 || row < 0)  
         {
            draggedPiece.setXpos(draggedPiece.getCol() * 
                                 width+(width * 5 / 90));
            draggedPiece.setYpos(draggedPiece.getRow() * 
                                 width+(width * 5 / 90));
         }
         else
         {
            validMove = draggedPiece.isMoveValid(sq[col][row].isOccupiable,
                              sq[col][row].hasChecker, col, row, boardRef);
            mustJump = players[currentPlayer].playerMustJump(boardRef);
            doesJump = (Math.abs(col-draggedPiece.getCol()) == 2);

            // if this is a valid move
            if (validMove && (!mustJump || (mustJump && doesJump)))
            {
               if (Math.abs(col-draggedPiece.getCol()) == 2)
               {
                  playerIsMidJump = true;
               }

               draggedPiece.executeMove(col, row, boardRef);

               if (row == 7 || row == 0)
               {
                  if (!(sq[col][row].contents.isKing()))
                  {
                     sq[col][row].contents = new King(sq[col][row].contents);
                     ch[sq[col][row].contents.player.getPlayerNumber()]
                       [sq[col][row].contents.getCheckerNumber()] 
                          = sq[col][row].contents;
                     sq[col][row].contents.player.checkers
                       [sq[col][row].contents.getCheckerNumber()]
                          = sq[col][row].contents;
                     playerIsMidJump = false;
                  }
               }
               
               mustJump = players[currentPlayer].
                     playerMustJump(boardRef, draggedPiece.getCheckerNumber());

               if (!(mustJump && playerIsMidJump))
               {
                  playerIsMidJump = false;
                  currentPlayer = players[currentPlayer].endTurn();
                  
                  if (!players[currentPlayer].mayMove(boardRef))
                  {
                     status1.setText("Game over: " + players[currentPlayer].
                                   name + " loses, " + players[currentPlayer].
                                   opponent.name + " wins!");
                  }
                  else
                  {
                     mustJump = players[currentPlayer].
                                       playerMustJump(boardRef);
                     
                     status1.setText("It is now " + players[currentPlayer].
                                      name + "'s turn.");
                                     
                     if (mustJump)
                     {
                        status1.setText(status1.getText() + "  Must jump.");
                     }
                  }
               }

            }//end if
            else
            {
               //Puts checker back to original pos
               draggedPiece.setXpos(draggedPiece.getCol() * 
                                    width+(width * 5 / 90));
               draggedPiece.setYpos(draggedPiece.getRow() * 
                                    width+(width * 5 / 90));
            }//end else
         }
         if (!playerIsMidJump)
         {
            draggedPiece = new Pawn ();
         }
         repaint();
      }
   }

   /**
     *  This method is called in the event that the board is resized
     *  @param e
    */
     
   public void componentResized(ComponentEvent e)
   {
      if (notReady)
         return;
      
      width = (this.getSize().height < this.getSize().width) ?
               this.getSize().height / 8 : this.getSize().width / 8;   
      for (int col = 0; col < 8; col++)
      {
         for (int row = 0; row < 8; row++)
         {
            sq[col][row].setWidth(width);
            sq[col][row].setXpos(col * width);
            sq[col][row].setYpos(row * width);
            if(sq[col][row].hasChecker)
            {
               sq[col][row].contents.setWidth(width * 8 / 9);
               sq[col][row].contents.setXpos(sq[col][row].contents.
                  getCol() * width + (width * 5 / 90));
               sq[col][row].contents.setYpos(sq[col][row].contents.
                  getRow() * width + (width * 5 / 90));
            }
         }
      }
      repaint();
   }
   /**
     *  This method overrides an interface method
     *  @param e
    */ 
   public void componentHidden(ComponentEvent e)
   {
   }
   
   /**
     *  This method overrides an interface method
     *  @param e
    */ 
   public void componentMoved(ComponentEvent e)
   {
   }

   /**
     *  This method overrides an interface method
     *  @param e
    */      
   public void componentShown(ComponentEvent e)
   {
   }
   
   /**
    *   This method is the driver of the Board.  It creates a
    *   new Board and calls the method setUpBoard.
    *   public static
    *   @param args    not currently used
   */
   public static void main(String [] args)
   {
      Board b = new Board();
      b.setUpBoard();
      b.boardRef = b;
      notReady = false;
      b.repaint();
   }//end main
}//end Board class