package prolog.treeview;

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;

/**
 * this is the implementation of the default node renderer rendering any object
 */
public class DefaultNodeRenderer
	implements
		INodeRenderer
{
	/**
	 * the default node size of this default node renderer ;-)
	 */
	protected static Dimension gvDefaultSize = new Dimension( 3, 20 );

	/**
	 * stores a component for calculating string width and height
	 */
	protected JComponent component = null;

	/**
	 * constructor
	 */
	public DefaultNodeRenderer()
	{
	}

	/**
	 * renders the given object into the given graphic context
	 * @param g - the graphic context to render into
	 * @param rect - the rect where to render into
	 * @param obj - the node content that should be rendered
	 */
	public void renderNode( Graphics2D g, Rectangle rect, Object obj )
	{
		prolog.ui.UiUtil.paintCenteredCell(
			g,
			rect,
			obj != null ? obj.toString() : "",
			Color.orange,
			Color.darkGray );
	}

	/**
	 * calculates the require size this renderer require to render
	 * the given object
	 * @return the size of the rendered object
	 */
	public Dimension calculateDimension( Object obj )
	{
		if( this.component != null )
		{
			Graphics g = component.getGraphics();
			FontMetrics fm = g.getFontMetrics();
			Rectangle2D r =
				fm.getStringBounds(
					obj.toString(),
					g );
			return
				new Dimension(
					((int)r.getWidth()) + 30, // <- 30 = hack because when having chars like '(' or ';' the result returned by getStringBounds is not right
					((int)r.getHeight()) + 4 );
		}
		return gvDefaultSize;
	}

	/**
	 * sets the component to render in. with
	 * this reference the node renderer
	 * is able to fetch a graphic context and
	 * to calculate the width of a string on screen.
	 */
	public void setComponent( JComponent c )
	{
		this.component = c;
	}
}
