package litebrite.layoutbased;

import java.awt.*;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.border.*;

public class LiteBriteBoard extends Container
{
  private Color currentColor;

  public LiteBriteBoard(int numberOfRows, int numberOfColumns)
  {
    // Check that we have valid arguments
    if (numberOfColumns < 1 || numberOfColumns < 1)
    {
      throw new IllegalArgumentException("The number of rows and columns must be greater than 0.");
    }

    // Remember the size of the board and set the default color
    setLayout(new GridLayout(numberOfRows, numberOfColumns));
    currentColor = Color.white;

    // Make a simple border for the panels
    Border border = new LineBorder(Color.black, 1, true);

    // Fill the board with panels set to the default color
    for (int i = 0; i < numberOfColumns * numberOfRows; i++)
    {
      JPanel panel = new JPanel();
      panel.setBackground(currentColor);
      panel.setBorder(border);
      add(panel);
    }

    // Make a mouse adapter to handle mouse presses and drags
    MouseAdapter mouseAdapter = new MouseAdapter()
    {
      @Override
      public void mousePressed(MouseEvent e)
      {
        colorPanelAt(e.getPoint());
      }

      @Override
      public void mouseDragged(MouseEvent e)
      {
        colorPanelAt(e.getPoint());
      }

      private void colorPanelAt(Point p)
      {
        // If there is a panel at the given location set its color to be the
        // current color
        Component c = getComponentAt(p);
        if (c != null && c instanceof JPanel)
        {
          c.setBackground(currentColor);
        }
      }
    };

    addMouseListener(mouseAdapter);
    addMouseMotionListener(mouseAdapter);
  }

  public Color getCurrentColor()
  {
    return currentColor;
  }

  public void setCurrentColor(Color currentColor)
  {
    this.currentColor = currentColor;
  }
}
