package mosaic_draw;

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

/**
 * This class represents a menu bar that contains commands for the MosaicDraw application.
 * The menus are set up so that when the user selects one of the commands, the
 * doMenuCommand(commandName) method is called in the Controller associated with
 * the mosaic.
 * <p>Note that the menus are actually created in the createMenu() method, and new
 * commands and menus can be added in that method.
 */
public class Menus extends JMenuBar {
	
	private Controller controller;  // The Controller to which the menu commands are sent.

	public Menus(Controller controller, boolean runningAsApplet) {
		this.controller = controller;
		createMenus(runningAsApplet);
		addListener();
	}
	
	private void addListener() {
		ActionListener listener = new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				JMenuItem item = (JMenuItem)evt.getSource();
				String command = item.getText();
				controller.doMenuCommand(command);
			}
		};
		int menuCount = getComponentCount();
		for (int i = 0; i < menuCount; i++) {
			JMenu menu = (JMenu)getComponent(i);
			int itemCount = menu.getMenuComponentCount();
			for (int j = 0; j < itemCount; j++) {
				if (menu.getMenuComponent(j) instanceof JMenuItem) {
					JMenuItem item = (JMenuItem)menu.getMenuComponent(j);
					item.addActionListener(listener);
				}
			}
		}
	}
	
	/**
	 * This is where the menus are actually created and added to the menu bar.
	 * @param runningAsApplet
	 */
	private void createMenus(boolean runningAsApplet) {
		// TODO: Possibly add more commands and menus.
		
		// Create the menus.
		
		JMenu controlMenu = new JMenu("Control");
		JMenu colorMenu = new JMenu("Color");

		// Add the menus to the menu bar.
		
		add(controlMenu);
		add(colorMenu);
		
		// Add commands to the "Control" menu.

		controlMenu.add("Clear");
		controlMenu.add("Fill");
		controlMenu.add("Frame");
		if (!runningAsApplet) {  
					// These are commands that won't work in an applet; they are added
					// only if the mosaic draw appliation is NOT running as an applet.
			controlMenu.addSeparator();
			controlMenu.add("Save PNG Image...");
			controlMenu.add("Save JPEG Image...");
			controlMenu.addSeparator();
			controlMenu.add("Quit");
		}
		
		// Add commands to the "Color" menu.
		
		colorMenu.add("Set Color...");
		colorMenu.addSeparator();
		colorMenu.add("No Randomness");
		colorMenu.add("Some Randomness");
		colorMenu.add("Moderate Randomness");
		colorMenu.add("Much Randomness");

	} // end createMenus
	
}

