/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.editors.layout.figures;

import java.util.Iterator;

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.swt.graphics.Font;

import org.maskat.core.layout.Grid;
import org.maskat.core.layout.GridHeader;
import org.maskat.ui.editors.layout.editparts.GridHeaderEditPart;

public class GridFigure extends Label {
	public static Font DEFAULT_FONT = new Font(null, "Arial", 8, 0);
	
	private Grid grid;

	public GridFigure(Grid grid) {
		super();
		this.grid = grid;
		setForegroundColor(ColorConstants.black);
		setFont(DEFAULT_FONT);
		setBorder(new LineBorder());
		setLayoutManager(new XYLayout());
	}

	protected void paintFigure(Graphics graphics) {
		super.paintFigure(graphics);
		graphics.translate(bounds.x, bounds.y);

		if (grid.getName() != null) {
			graphics.drawText(grid.getName(), 0, 0);
		}

		Iterator headersIt = grid.getHeadersIt();
		if (headersIt != null) {
			int currentX = 0;
			// 垂直線を画く
			while (headersIt.hasNext()) {
				GridHeader header = (GridHeader) headersIt.next();
				currentX += GridHeaderEditPart.toHeaderDisplayWidth(header.getWidth());
				graphics.drawLine(currentX, GridHeaderEditPart.headerTop + 1, currentX,
						grid.getHeight());
			}

			// 水平線を画く
			int lineHeight = 0;
			try {
				lineHeight = grid.getLineHeight();
			} catch (NumberFormatException e) {
			}
			lineHeight = Math.max(lineHeight, 5);
			int currentY = GridHeaderEditPart.headerHeight + GridHeaderEditPart.headerTop + 1;
			int headerTotalWidth = grid.headerTotalWidth();
			while (currentY <= grid.getHeight()) {
				graphics.drawLine(0, currentY, headerTotalWidth, currentY);
				currentY += lineHeight;
			}
		}
		graphics.translate(-bounds.x, -bounds.y);
	}
}
