// Copyright 2006 by Basil Vandegriend.  All rights reserved.

package com.basilv.core.richui;

import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.font.LineMetrics;

import javax.swing.Icon;

import com.basilv.core.Assert;

/**
 * Represents an icon that displays text.
 *
 */
public class TextIcon implements Icon
{
	private static final long serialVersionUID = 1L;

	private Dimension size;
	private String text;
	
	public TextIcon(Dimension size, String text) {
		Assert.notNull("size", size);
		Assert.notNull("text", text);
		
		this.size = size;
		this.text = text;
	}

	public int getIconHeight() {
		return size.height;
	}

	public int getIconWidth() {
		return size.width;
	}

	public void paintIcon(Component c, Graphics g, int x, int y) {
		g.setColor(c.getForeground());
		g.setFont(c.getFont());
		
		FontMetrics fontMetrics = g.getFontMetrics();
		LineMetrics lineMetrics = fontMetrics.getLineMetrics(text, g);
		int xAdjust = fontMetrics.stringWidth(text);
		int yAdjust = (int) lineMetrics.getHeight();
		
		// Center vertically and horizontally.
		int drawX = x + (size.width - xAdjust) / 2;

		// Add ascent since draw from the baseline.
		int drawY = y + (size.height - yAdjust) / 2 + (int) lineMetrics.getAscent();
		
		g.drawString(text, drawX, drawY);
	}

}

