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

public class Bar extends Canvas {
	static Color invisible, unsorted, sorted, mergeHead;
	static int width, heightMultiple;
	static boolean alreadyInit = false;
	static int maxValue;
	
	/* The value that the bar represents.  The bar's height is
		value * heightMultiple
	*/
	int value;	
	boolean isInvisible;
	
	public static void setMaxValue(int theMaxValue) {
		maxValue = theMaxValue;
	}

	public static void init(
		Color newInvisible, 
		Color newUnsorted, 
		Color newSorted, 
		Color newMergeHead, 
		int newWidth, int newHeightMultiple) {

		if ( !alreadyInit ) {
			invisible = newInvisible;
			unsorted = newUnsorted;
			sorted = newSorted;
			mergeHead = newMergeHead;
			width = newWidth;
			heightMultiple = newHeightMultiple;
			alreadyInit = true;
		}
	}

	public static void init(Color bg, int newWidth, int newHeightMultiple) {
		init(bg,Color.blue,Color.green,Color.red, newWidth, newHeightMultiple);
	}

	// Return the size of a bar that is of this given value.
	// Should be called only after init() or after some Bar has been created.
	public static Dimension getValueDimension(int value) {
		return new Dimension(width, heightMultiple*value);
	}

    public void paint(Graphics g) {
//System.out.println("  Bar of height "+getValue()+" colour "+getForeground()+" painting");
		update(g);
    }
        
    public void update(Graphics g) {
		Dimension d = size();
		int w=d.width, h=d.height, bh=value*heightMultiple;
		g.setColor(getBackground());
		g.fillRect(0,0,w,h-bh);
// System.out.println("  update bar of height "+getValue()+" is invisible "+isInvisible);
		if ( isInvisible ) {
			g.fillRect(0,h-bh,w,bh);
		} else {
			g.setColor(getForeground());
			g.fill3DRect(0,h-bh,w,bh,true);
		}
    }
        
	// Bar.init must be called before any bars are created.
	public Bar() {
		setValue(1);
		setInvisible();
	}

	public Bar(int value) {
		setValue(value);
		setInvisible();
	}

	public int getValue() {
		return value;
	}

	public void setValue(int value) {
		this.value = value;
// System.out.println("  Bar value := "+value);
		repaint();
	}

	public void setInvisible() {
// System.out.println("  Bar "+value+" invisible");
		setForeground(invisible);
		isInvisible = true;
		repaint();
	}

	public void setUnsorted() {
// System.out.println("  Bar "+value+" unsorted");
		setForeground(unsorted);
		isInvisible = false;
		repaint();
	}

	public void setSorted() {
// System.out.println("  Bar "+value+" sorted");
		setForeground(sorted);
		isInvisible = false;
		repaint();
	}

	public void setMergeHead() {
// System.out.println("  Bar "+value+" mergeHead");
		setForeground(mergeHead);
		isInvisible = false;
		repaint();
	}

	public Dimension preferredSize() {
		return new Dimension(width, maxValue*heightMultiple);
	}
	public Dimension minimumSize() {
		return new Dimension(width, maxValue*heightMultiple);
	}
}
