import javax.swing.JPanel;
import javax.swing.JComboBox;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class SimObjectChooser extends JPanel {
	// OVERVIEW: SimObjectChooser manipulates the interface for selecting objects
	//    and maintains state for the current object type.  
	//
	// When clicking on a spot on the grid, it will be set to this class.
	
	// Rep:
	private Class selectedClass;
	private JComboBox combolist;
	private String[] classes;

	//@invariant combolist != null;
	
	SimObjectChooser()
	// EFFECT: Initializes this to a SimObjectChooser with no classes.
	{
		selectedClass = null;
		classes = null;
		combolist = new JComboBox();

		combolist.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JComboBox cb = (JComboBox) e.getSource();
				String classname = (String) cb.getSelectedItem();
				setSelectedClass(classname);
			}
		});

		add(combolist);
	}

	public void addClass(String className) throws ClassNotFoundException
	// MODIFIES: this, the display panel
	// EFFECTS: If className is the name of a loadable Java class, sets the current object
	//    to the type loaded by className. If className is not available, throws ClassNotFoundException. 
	{
		Class newClass = Class.forName(className);
		// throws ClassNotFoundException if not found

		String[] oldclasses = classes;

		if (oldclasses == null) {
			classes = new String[1];
			selectedClass = newClass;
		} else {
			classes = new String[oldclasses.length + 1];
		}

		if (oldclasses != null) {
			for (int i = 0; i < oldclasses.length; i++) {
				classes[i] = oldclasses[i];
			}
		}

		classes[classes.length - 1] = className;
		combolist.addItem(className);
	}

	public Class getSelectedClass()
	// EFFECTS: Returns the currently selected class (possibly null).
	{
		return selectedClass;
	}

	public void setSelectedClass(String classname)
	// MODIFIES: this
	// EFFECTS: Sets the currently selected class to the class associated
	//    with the button press (described by the ActionEvent).
	{
		try {
			Class newClass = Class.forName(classname);
			selectedClass = newClass;
		} catch (java.lang.ClassNotFoundException ex) {
			System.err.println(
				"BUG: Selected class is not available: " + classname);
			ex.printStackTrace();
		}
	}
}

//Class borrowed from Saturday Night Simulator and CS201J Website - PS5