package j3deditor.bin.components;

import j3deditor.bin.util.Utilities;

import java.awt.Component;

import java.awt.Container;

import java.util.ArrayList;

import javax.swing.JPanel;


/**
 * The <code>MultiPanel</code> node controls which of its children
 * will be attached to the given container.
 * If has no children can be attached to a container itself as empty
 * <code>JPanel</code>.
 *
 * @author Risto Seene
 */
public class MultiPanel extends JPanel{


	/** list of children */
	private ArrayList<Component> panels;

	/** parent of this panel */
	private Container parent;

	/** currently shown component */
	private Component current;


	/**
	 * Creates an instance of <code>MultiPanel</code>
	 * which can attach its children to the given container.
	 *
	 * @param parent
	 *	container where the children can be attached to
	 */
	public MultiPanel(Container parent){
		this.parent = parent;
		panels = new ArrayList<Component>();
		current = this;
	}


	/**
	 * Adds new child to this multipanel.
	 *
	 * @param panel
	 *	new component
	 */
	public void addPanel(Component panel){
		panels.add(panel);
	}


	/**
	 * Removes one component at the specified index.
	 *
	 * @param index
	 *	index of the component that will be removed
	 */
	public void removePanel(int index){
		panels.remove(index);
	}


	/**
	 * Removes the specified component.
	 *
	 * @param panel
	 *	the component that will be removed
	 */
	public void removePanel(Component panel){
		removePanel(panels.indexOf(panel));
	}


	/**
	 * Replaces the currently shown component.
	 *
	 * @param index
	 *	index of child to be shown
	 */
	public void setActive(int index){
		try{
			Component newPanel = panels.get(index);
			int nr = getCompNumber(current);
			parent.remove(current);
			parent.add(newPanel, nr);
			current = newPanel;
			parent.validate();
			current.repaint();
		} catch(Throwable t){
			Utilities.out.throwWarning(t);
		}
	}


	/**
	 * Replaces the currently shown component.
	 *
	 * @param panel
	 *	child to be shown
	 */
	public void setActive(Component panel){
		setActive(panels.indexOf(panel));
	}

	private int getCompNumber(Component current){
		for(int i = 0; i < parent.getComponentCount(); i++){
			if(parent.getComponent(i) == current){
				return i;
			}
		}
		return -1;
	}


	/**
	 * Replaces the currently shown component with the next child.
	 */
	public void activateNextPanel(){
		int active = panels.indexOf(current);
		if(active < panels.size() - 1){
			setActive(active + 1);
		} else {
			setActive(0);
		}
	}

}
