// Copyright 1996, David Neto
import java.awt.*;
import java.util.*;

public class BarPanel extends Panel {
	GridBagLayout gridBag;
	GridBagConstraints c;
	int maxValue;
	Vector bars;

	void initGridBag() {
		gridBag = new GridBagLayout();
		setLayout(gridBag);
		c = new GridBagConstraints();
		c.weighty = 1.0;
		c.gridheight = GridBagConstraints.REMAINDER;
		c.anchor = GridBagConstraints.SOUTH;
	}

	public BarPanel() {
		initGridBag();
		bars = new Vector();
		setMaxValue(15); // No reason; just an example.
	}

	public BarPanel(int maxValue, int num) {
		initGridBag();
		bars = new Vector(num);
		setMaxValue(maxValue);
		for (int i=0; i<num; i++) addBar(1);
	}

	public BarPanel(int maxValue, int valueArray[], int lo, int hi) {
		initGridBag();
		bars = new Vector(hi-lo);
		setMaxValue(maxValue);
		for (int i=lo; i<hi; i++) addBar(valueArray[i]);
	}

	public void addBar() {
		addBar(1);
	}

	public void addBar(int value) {
		Bar.setMaxValue(maxValue);
		Bar newBar = new Bar(value);
		bars.addElement(newBar);
		gridBag.setConstraints(newBar,c);
		add(newBar);
	}

	// We need these two functions because we want to make all the BarPanels 
	// the same height, no matter what the values of its constituent bars.
	// (Maybe add inset too.)
	public Dimension preferredSize() {
		return minimumSize();
	}

	public Dimension minimumSize() {
		Dimension biggestBar = Bar.getValueDimension(maxValue);
		biggestBar.width = biggestBar.width * bars.size() +2;
		biggestBar.height += 2;

		return biggestBar;
	}

	public int getBarValue(int i) {
		return ((Bar)bars.elementAt(i)).getValue();
	}

	public void setBarValue(int i, int value) {
		((Bar)bars.elementAt(i)).setValue(value);
	}

	public void setBarInvisible(int i) {
		((Bar)bars.elementAt(i)).setInvisible();
	}

	public void setBarUnsorted(int i) {
		((Bar)bars.elementAt(i)).setUnsorted();
	}

	public void setBarSorted(int i) {
		((Bar)bars.elementAt(i)).setSorted();
	}

	public void setBarMergeHead(int i) {
		((Bar)bars.elementAt(i)).setMergeHead();
	}

	public void paint(Graphics g) {
		update(g);
	}

	public void update(Graphics g) {
		Dimension d = size();
		g.setColor(getBackground());
		g.fillRect(0,0,d.width-1,d.height-1);
		g.setColor(getForeground());		// Now draw an X
		g.drawRect(0,0,d.width-1,d.height-1);
	}

	public void setMaxValue(int maxValue) {
		this.maxValue = maxValue;
	}
}
