/*
 * Copyright 2006 Mask@ Project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.maskat.ide.gef.figure;

import java.util.Iterator;

import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.Label;
import org.maskat.framework.screendef.GridDef;
import org.maskat.framework.screendef.GridHeaderDef;
import org.maskat.ide.gef.editparts.GridHeaderEditPart;

public class MaskatGridFigure extends Label {

	private GridDef grid;

	public MaskatGridFigure(GridDef grid) {
		super();
		this.grid = grid;
	}

	protected void paintFigure(Graphics graphics) {
		super.paintFigure(graphics);
		if (grid != null) {
			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()) {
					GridHeaderDef header = (GridHeaderDef) headersIt.next();
					currentX += GridHeaderEditPart
							.toHeaderDisplayWidth(header.getWidth());
					graphics.drawLine(currentX, GridHeaderEditPart.headerTop + 1,
							currentX, grid.getHeight());
				}

				// 水平線を画く
				int lineHeight = 0;
				try {
					lineHeight = Integer.parseInt(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);
	}
}
