/*
 * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
 */

package glass.rain;

import com.sun.glass.ui.*;
import com.sun.rain.graphics.*;
import com.sun.rain.shapes.*;

public class TextView extends View.EventHandler
{
    private View view;

    public TextView(final String fontName)
    {
        view = Application.GetApplication().createView(new TextGraphics(fontName));
        view.setEventHandler(this);
    }

    public View getView() {
        return view;
    }
    
    public void handleRunLoop(View view, long time)
    {
        Pen pen = view.getPen();
        pen.begin();
        {
            pen.paint(time, view.getWidth(), view.getHeight());
        }
        pen.end();
    }
    
    public void setColors(final Color foreground, final Color background)
    {
        TextGraphics g = (TextGraphics)view.getPen();
        g.setColors(foreground, background);
    }
    
    public void setText(final String text, final int fontSize)
    {
        TextGraphics g = (TextGraphics)view.getPen();
        g.setText(text, fontSize);
    }
}

class TextGraphics extends Graphics2D
{
    String text;
    Font font;
    String fontName;
    float fontSize;
    Color foreground = Color.WHITE;
    Color background = Color.BLACK;
    
    public TextGraphics(final String fontName)
    {
        this.fontName = fontName;
        this.fontSize = 20;
        this.font = new Font(this.fontName, Font.Type.PLAIN, this.fontSize);
    }
    
    @Override
    public void paint(long timeStamp, int width, int height)
    {
        if (this.fontSize != this.font.getSize())
        {
            this.font = new Font(this.fontName, Font.Type.PLAIN, this.fontSize);
        }
        
        set(this.background);
        fillRect(0, 0, width, height);

        if (this.text != null)
        {
            Rectangle bounds = this.font.getBoundingBox(this.text);
            set(this.font);
            set(this.foreground);
            draw(this.text, (width-bounds.getWidth())/2, (height-bounds.getHeight())/2);
        }
    }
    
    public void setColors(final Color foreground, final Color background)
    {
        this.foreground = foreground;
        this.background = background;
    }
    
    public void setText(final String text, final int fontSize)
    {
        this.text = text;
        this.fontSize = fontSize;
    }
}
