import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.LinkedList;

public class SuicideChessApplet extends JApplet implements MouseListener, ActionListener
{
    private Board board;
    private int selectedSquare = -1;
    private boolean gameOver   = false;
    private Image whitePawn;
    
    private int numAiMovesMadeThisGame  = 0;
    private int numAiOpeningRandomMoves = 1;
    private int searchDepth             = 10;

    private Button newGameBtn                    = new Button("New Game");
    private Choice choiceSearchDepth             = new Choice();
    private Choice choiceNumAiOpeningRandomMoves = new Choice();
    private Choice choiceBlackOrWhite            = new Choice();

    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("New Game"))
        {
            if(this.choiceSearchDepth.getSelectedItem().equals("1"))
            {
                this.searchDepth = 1;
            }
            else if(this.choiceSearchDepth.getSelectedItem().equals("10"))
            {
                this.searchDepth = 10;
            }
            else if(this.choiceSearchDepth.getSelectedItem().equals("25"))
            {
                this.searchDepth = 25;
            }
            else if(this.choiceSearchDepth.getSelectedItem().equals("50"))
            {
                this.searchDepth = 50;
            }
            else if(this.choiceSearchDepth.getSelectedItem().equals("100"))
            {
                this.searchDepth = 100;
            }
            else if(this.choiceSearchDepth.getSelectedItem().equals("200"))
            {
                this.searchDepth = 200;
            }

            if(this.choiceNumAiOpeningRandomMoves.getSelectedItem().equals("0"))
            {
                this.numAiOpeningRandomMoves = 0;
            }
            else if(this.choiceNumAiOpeningRandomMoves.getSelectedItem().equals("1"))
            {
                this.numAiOpeningRandomMoves = 1;
            }
            else if(this.choiceNumAiOpeningRandomMoves.getSelectedItem().equals("2"))
            {
                this.numAiOpeningRandomMoves = 2;
            }
            else if(this.choiceNumAiOpeningRandomMoves.getSelectedItem().equals("3"))
            {
                this.numAiOpeningRandomMoves = 3;
            }
            else if(this.choiceNumAiOpeningRandomMoves.getSelectedItem().equals("4"))
            {
                this.numAiOpeningRandomMoves = 4;
            }
            else if(this.choiceNumAiOpeningRandomMoves.getSelectedItem().equals("5"))
            {
                this.numAiOpeningRandomMoves = 5;
            }            

            newGame();

            if(this.choiceBlackOrWhite.getSelectedItem().equals("Black"))
            {
                move();
            }
            repaint();
        }
    }

    public void mouseEntered (MouseEvent me) {} 
    public void mousePressed (MouseEvent me)
    {
        if(this.gameOver)
        {
            return;
        }
        int squareIndex = getSquareIndexFromMouseCoords(me);
        if ((board.isWhitesTurn() && (board.squaresContainingWhitePieces() & (1L << squareIndex)) != 0) ||
           (!board.isWhitesTurn() && (board.squaresContainingBlackPieces() & (1L << squareIndex)) != 0))
        {
            this.selectedSquare = squareIndex;
        }
        else
        {
            this.selectedSquare = -1;
        }
        repaint();
    }

    public void mouseReleased (MouseEvent me)
    {
        if(gameOver || this.selectedSquare == -1)
        {
            return;
        }
        int squareIndex = getSquareIndexFromMouseCoords(me);
        Move m = new Move(this.selectedSquare, squareIndex);
        
        LinkedList<Move> legalMoves = this.board.isWhitesTurn() ? this.board.legalWhiteMoves() : this.board.legalBlackMoves();
        if(legalMoves.contains(m))
        {
            if(this.board.isTakingMove(m))
            {
                this.board.doMove(m);

                // If all pieces of either colour have been taken then assume the last move won then game
                if(this.board.squaresContainingWhitePieces() == 0 || this.board.squaresContainingBlackPieces() == 0)
                {
                    JOptionPane.showMessageDialog(null, this.board.isWhitesTurn() ? "White wins" : "Black wins");
                    this.gameOver = true;
                    return;
                }

                this.selectedSquare = -1;
                repaint();
                // If all pieces of either colour have been taken then assume the last move won then game
                if(this.board.squaresContainingWhitePieces() == 0 || this.board.squaresContainingBlackPieces() == 0)
                {
                    JOptionPane.showMessageDialog(null, this.board.isWhitesTurn() ? "White wins" : "Black wins");
                    this.gameOver = true;
                    return;
                }
                else
                {
                    move();
                }
            }
            else
            {
                boolean mustTake = false;
                for(int i = 0; i < legalMoves.size(); i++)
                {
                    Move m2 = legalMoves.get(i);
                    if(this.board.isTakingMove(m2))
                    {
                        JOptionPane.showMessageDialog(null, "You must take your opponent's piece");
                        mustTake = true;
                        this.selectedSquare = -1;
                        repaint();
                        break;
                    }
                }
                if(!mustTake)
                {
                    this.board.doMove(m);
                    this.selectedSquare = -1;
                    repaint();
                    // If all pieces of either colour have been taken then assume the last move won then game
                    if(this.board.squaresContainingWhitePieces() == 0 || this.board.squaresContainingBlackPieces() == 0)
                    {
                        JOptionPane.showMessageDialog(null, this.board.isWhitesTurn() ? "White wins" : "Black wins");
                        this.gameOver = true;
                        return;
                    }
                    else
                    {
                        move();
                    }
                }
            }
        }
        this.selectedSquare = -1;
        repaint();
    }

    public void mouseExited (MouseEvent me) {}
    public void mouseClicked (MouseEvent me) {}

    private int getSquareIndexFromMouseCoords(MouseEvent me)
    {
        Point p = new Point(me.getX() / 50, me.getY() / 50);
        int squareIndex = p.x + (p.y * 8);
        if(squareIndex >= 0 &&
           squareIndex < 64)
        {
            return squareIndex;
        }
        else
        {
            return -1;
        }
    }

    public void init()
    {
        // this is a workaround for a security conflict with some browsers
        // including some versions of Netscape & Internet Explorer which do 
        // not allow access to the AWT system event queue which JApplets do 
        // on startup to check access. May not be necessary with your browser. 
        JRootPane rootPane = this.getRootPane();    
        rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

        this.setLayout(new BorderLayout());
        Panel p = new Panel();
        p.setLayout(new FlowLayout());
        this.add(p, BorderLayout.PAGE_END);

        this.choiceNumAiOpeningRandomMoves.add("0");
        this.choiceNumAiOpeningRandomMoves.add("1");
        this.choiceNumAiOpeningRandomMoves.add("2");
        this.choiceNumAiOpeningRandomMoves.add("3");
        this.choiceNumAiOpeningRandomMoves.add("4");
        this.choiceNumAiOpeningRandomMoves.add("5");
        this.choiceNumAiOpeningRandomMoves.select("1");
        Panel p2 = new Panel();
        p2.setLayout(new GridLayout(0, 2));
        p2.add(new Label("# AI opening random moves"));
        p2.add(this.choiceNumAiOpeningRandomMoves);

        this.choiceSearchDepth.add("1");
        this.choiceSearchDepth.add("10");
        this.choiceSearchDepth.add("25");
        this.choiceSearchDepth.add("50");
        this.choiceSearchDepth.add("100");
        this.choiceSearchDepth.add("200");
        this.choiceSearchDepth.select("10");
        p2.add(new Label("Search Depth"));
        p2.add(this.choiceSearchDepth);

        this.choiceBlackOrWhite.add("White");
        this.choiceBlackOrWhite.add("Black");
        this.choiceBlackOrWhite.select("Black");
        p2.add(new Label("Play as"));
        p2.add(this.choiceBlackOrWhite);

        p.add(p2);

        newGameBtn.setPreferredSize(new Dimension(75, 50));
        p.add(newGameBtn);
        newGameBtn.addActionListener(this);

        Icons.loadIcons(this);
        addMouseListener(this);
        newGame();
        move();
    }
    
    public void newGame()
    {
        this.gameOver = false;
        this.board = new Board();
        this.numAiMovesMadeThisGame = 0;
    }

    public void move()
    {
        // If all pieces of either colour have been taken then assume the last move won then game
        if(this.board.squaresContainingWhitePieces() == 0 || this.board.squaresContainingBlackPieces() == 0)
        {
            JOptionPane.showMessageDialog(null, this.board.isWhitesTurn() ? "White wins" : "Black wins");
            this.gameOver = true;
            return;
        }

        if(this.numAiMovesMadeThisGame < this.numAiOpeningRandomMoves)
        {
            LinkedList<Move> legalMoves = board.isWhitesTurn() ? board.legalWhiteMoves() : board.legalBlackMoves();
            Move m;
            do
            {
                int randomIndex = (int)(Math.random() * legalMoves.size());
                m = legalMoves.get(randomIndex);
                legalMoves.remove(randomIndex);
            }
            while(!board.isTakingMove(m) && !legalMoves.isEmpty());
            this.board.doMove(m);
            this.numAiMovesMadeThisGame++;
        }
        else
        {
            this.board.makePerfectMove(this.searchDepth);
        }

        if(this.board.squaresContainingWhitePieces() == 0 || this.board.squaresContainingBlackPieces() == 0)
        {
            JOptionPane.showMessageDialog(null, this.board.isWhitesTurn() ? "White wins" : "Black wins");
            this.gameOver = true;
            return;
        }
        else if(this.board.listAllLegalMoves().isEmpty())
        {
            JOptionPane.showMessageDialog(null, "Stale mate");
            this.gameOver = true;
            return;
        }
    }

    public void paint(Graphics g)
    {
        Image offscreen = createImage(500, 500);
        Graphics g2 = offscreen.getGraphics();
        board.draw(g2, this.selectedSquare, this);
        g.drawImage(offscreen, 0, 0, this);
    }
}

