package cnp.ew.displayer;
import java.awt.*;
import java.util.*;

import cnp.ew.lightweight.*;
import cnp.ew.util.*;
/**
 * A displayer that will visibly indicate that a certain
 * prefix of a string has been selected by displaying the
 * prefixed text in a different color.
 *
 * @version        $Version$
 * @author         $Author: Ken $
 */
public class CpPrefixedStringDisplayer extends CpAbstractSelectableTextDisplayer
{

    public Color prefixForeColor = Color.blue;

    String text;

    String prefixString="";

    public CpPrefixedStringDisplayer()
    {
        super();
        font = CpFonts.dialogPlainTwelve();
    }

    /**
     * Answer the preferred size for this displayable object.
     */
    public Dimension preferredSize(CpLightweightComponent c)
    {
        FontMetrics fontMetrics = getFontMetrics(c);
        return new Dimension(fontMetrics.stringWidth(text), fontMetrics.getHeight());
    }

    public void setText(String newText)
    {
        text = newText;
    }

    public String getText()
    {
        return text;
    }

    public void setPrefixString(String newPrefixString)
    {
        prefixString = newPrefixString;
    }


    public void paintIn(CpLightweightComponent c, Graphics g, Rectangle rect)
    {
        paintIn(c, g, rect.x, rect.y, rect.width, rect.height);
    }


    /**
     * Display the text using g.
     */
	public void paintIn(CpLightweightComponent c, Graphics g, int x, int y, int w, int h)
	{
        int startX, startY;
        FontMetrics fontMetrics;
        String nonPrefixText;

        if (font != null) {
	        g.setFont(font);
	    }

	    fontMetrics = getFontMetrics(c);
    	g.setColor(c.getBackground());
    	g.fillRect(x, y, w, h);

	    startX = x;
	    startY = y + fontMetrics.getAscent();

        if (prefixString.length() > 0) {
	        g.setColor(prefixForeColor);
	        g.drawString(prefixString, startX, startY);
    	    g.setColor(c.getForeground());
    	    nonPrefixText = text.substring(prefixString.length(), text.length());
    	    startX += fontMetrics.stringWidth(prefixString);
    	    g.drawString(nonPrefixText, startX, startY);
    	} else {
    	    g.setColor(c.getForeground());
    	    g.drawString(text, startX, startY);
    	}
    }
}