/**
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 *
 * Copyright (C)
 * <a href="http://www.inab.org">Spanish National Institute of Bioinformatics (INB)</a>
 * <a href="http://www.bsc.es">Barcelona Supercomputing Center (BSC)</a>
 * <a href="http://inb.bsc.es">Computational Node 6</a>
 */

package org.inb.biomoby.client.gui;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;

/**
 * @author Dmitry Repchevsky
 */

public final class StringPainter
{
    public static enum ALIGNMENT {LEFT, CENTER, RIGHT};
    
    private StringPainter() {}
    
    public static void drawString(Graphics2D g2d, String string, ALIGNMENT alignment)
    {
        Rectangle rec = g2d.getClipBounds();
        
        if (rec != null)
        {
            final double w = rec.getWidth();
            final double h = rec.getHeight();

            FontRenderContext context = g2d.getFontRenderContext();

            Font font;
            Rectangle2D bounds;
            int fSize = 36;

            do
            {
                font = new Font(Font.SANS_SERIF, Font.PLAIN, fSize--);
                bounds = font.getStringBounds(string, context);
            }
            while (bounds.getWidth() > w || bounds.getHeight() > h);
            
            final double x;
            switch(alignment)
            {
                case LEFT: x = rec.getX(); break;
                case RIGHT: x = rec.getX() + w - bounds.getWidth(); break;

                case CENTER: // pass through
                default: x = rec.getX() + (w - bounds.getWidth())/2;
            }
            
            g2d.setFont(font);
            LineMetrics lm = g2d.getFontMetrics().getLineMetrics(string, g2d);
            g2d.drawString(string, (int)x, (int)(rec.getY() + h - lm.getDescent()));
        }
    }
}
