import javax.swing.JOptionPane;
import javax.swing.JPanel;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

/**
 * create a toolbar for the paint window
 * 
 * @author Joe Wanstrath. Created Apr 2, 2008.
 */
public class Toolbar extends JPanel implements ActionListener {
	// private Canvas canvas;

	/**
	 * list of available tools
	 */
	public static final String[] tools = { "Pencil", "Paintbrush", "Line",
			"Oval", "Rectangle", "Polygon", "Spraycan", "Text", "Eraser" };

	private ArrayList<ToolButton> buttons = new ArrayList<ToolButton>();

	private int sides = 0;

	/**
	 * 
	 * create a toolbar linked to a canvas
	 * 
	 * @param canvas
	 *            the canvas
	 */
	public Toolbar() {
		this.setLayout(new GridLayout(0, 1));
		// this.canvas = canvas;
		for (int i = 0; i < tools.length; i++) {
			ToolButton b = new ToolButton(tools[i]);
			this.add(b);
			this.buttons.add(b);
			b.addActionListener(this);
			b.setBackground(Color.lightGray);
			if (this.buttons.get(i).getText().equals("Pencil")) {
				this.buttons.get(i).setActive(true);
				this.buttons.get(i).setBackground(Color.yellow);
			}
		}
	}

	/**
	 * 
	 * get the current active tool
	 * 
	 * @return tool name
	 */
	public String getActiveButton() {
		for (int i = 0; i < this.buttons.size(); i++) {
			if (this.buttons.get(i).isActive()) {
				return this.buttons.get(i).getText();
			}
		}
		return null;
	}

	/**
	 * 
	 * access number of sides for Polygon tool
	 * 
	 * @return sides
	 */
	public double getSides() {
		return this.sides;
	}

	public void actionPerformed(ActionEvent e) {
		for (int i = 0; i < this.buttons.size(); i++) {
			this.buttons.get(i).setActive(false);
		}
		((ToolButton) e.getSource()).setActive(true); // activates the most
		// recent clicked button
		for (int i = 0; i < this.buttons.size(); i++) {
			if (this.buttons.get(i).isActive()) {
				this.buttons.get(i).setBackground(Color.yellow);
			} else {
				this.buttons.get(i).setBackground(Color.lightGray);
			}
		}
		if (this.getActiveButton().equals("Polygon")) {
			String input1;
			input1 = JOptionPane.showInputDialog("Number of Sides for Polygon");
			this.sides = Integer.parseInt(input1);
		}
	}
}
