package puzzle;
import util.ActionPanel;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SquarePuzzleDisplay extends ActionPanel implements ActionListener{
    
    SquarePuzzle thePuzzle;
    JButton[][] tileButton;

    public SquarePuzzleDisplay(SquarePuzzle p){
        final int h=p.height;
        final int w=p.width;
        thePuzzle = p;
        tileButton = new JButton[h][];
        setLayout(new GridLayout(h,w));
        for (int i=0; i<h; i++) {
            tileButton[i] = new JButton[w];
            for (int j=0; j<w; j++) {
                tileButton[i][j] = new JButton(String.valueOf(thePuzzle.tile[i][j]));
                if (thePuzzle.tile[i][j]==0)
                    tileButton[i][j].setVisible(false);
                tileButton[i][j].setActionCommand(String.valueOf(i) + "," + String.valueOf(j));
                tileButton[i][j].addActionListener(this);
                add(tileButton[i][j]);
            }
        }
    }
    
    public void updateTiles() {
        for (int i=0; i<thePuzzle.height; i++)
            for (int j=0; j<thePuzzle.width; j++) {
                tileButton[i][j].setText(String.valueOf(thePuzzle.tile[i][j]));
                if (thePuzzle.tile[i][j]==0)
                    tileButton[i][j].setVisible(false);
                else tileButton[i][j].setVisible(true);
            }
    }

    public void actionPerformed (ActionEvent e) {
        String s = e.getActionCommand();
        int i,j,c;
        c = s.indexOf(',');
        i = (new Integer(s.substring(0,c))).intValue();
        j = (new Integer(s.substring(c+1))).intValue();
        thePuzzle.slidePiece(i,j);
        updateTiles();
	if (thePuzzle.isSolved())
	  JOptionPane.showMessageDialog(this,"Woo hoo!","Puzzle solved!",JOptionPane.INFORMATION_MESSAGE);
    }

    public void addActionListener(ActionListener ear) {
        for (int i=0; i<thePuzzle.height; i++)
            for (int j=0; j<thePuzzle.width; j++) {
                tileButton[i][j].addActionListener(ear);
            }
    }

}


