package cnp.ew.charts;

import cnp.ew.displayer.*;
import java.awt.*;
import cnp.ew.lightweight.*;
import cnp.ew.util.*;


// TBD: Fold into CpCategoryAxisDisplayer?
public class CpCenteredTickCategoryAxisDisplayer extends CpCategoryAxisDisplayer
{
    boolean drawTicks=true;
    static final int tickLength=4;
    static final int textTopMargin = 10;
    static final int labelGap = 10;

    public void paintIn(CpLightweightComponent lc, Graphics g, int x, int y, int w, int h)
    {

        int totalItems = model.getCategoryCount();
        int itemWidth = w/(totalItems - 1);
        FontMetrics metrics = lc.getFontMetrics();
        int fontAscent = metrics.getAscent();
        String string="";

        g.setColor(Color.black);

        int startX = x;
        g.setFont(font);
        for (int i=0; i < totalItems - 1; i++) {

            string = model.getCategoryForIndex(i);
            g.drawString(
                string,
                startX - metrics.stringWidth(string)/2,
                y + fontAscent + textTopMargin);

            if (drawTicks) {
                g.drawLine(startX, y, startX, y + tickLength);
            }

            startX += itemWidth;
        }
        if (drawTicks) {
            startX = x + w - 1;
            g.drawLine(startX, y, startX, y + tickLength);
        }
        g.drawString(
            model.getCategoryForIndex(totalItems - 1),
            startX - metrics.stringWidth(string)/2,
            y + fontAscent + textTopMargin);


        labelDisplayer.setText(model.getCategoriesLabel());
        int labelTop = metrics.getHeight() + textTopMargin + labelGap;
        labelDisplayer.paintIn(lc, g, x, y + labelTop, w, h - labelTop);
    }

    public int getLeftOrTopTickAlignmentOffset(CpLightweightComponent lc)
    {

        FontMetrics metrics = lc.getFontMetrics();
        return metrics.stringWidth(model.getCategoryForIndex(0)) / 2;
    }

    public int getRightOrBottomTickAlignmentOffset(CpLightweightComponent lc)
    {

        FontMetrics metrics = lc.getFontMetrics();
        return metrics.stringWidth(model.getCategoryForIndex(model.getCategoryCount() - 1)) / 2;
    }

    public Dimension preferredSize(CpLightweightComponent lc)
    {

        FontMetrics metrics = lc.getFontMetrics(font);
        labelDisplayer.setText(model.getCategoriesLabel());
        return new Dimension(20, metrics.getHeight() + textTopMargin + labelDisplayer.preferredSize(lc).height + labelGap);
    }
}

