/*
 * 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 org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.TreeSearch;
import org.eclipse.draw2d.geometry.Rectangle;

/**
 * マスカットのための特有機能はこのhelperクラスにある
 */
public class MaskatFigureHelper {

	private IFigure figure;

	private Rectangle PRIVATE_POINT = new Rectangle();

	MaskatFigureHelper(IFigure figure) {
		this.figure = figure;
	}

	/**
	 * comboItemのマウス選択動作対応
	 */
	protected IFigure findDescendantAtExcluding(int x, int y, TreeSearch search) {
		PRIVATE_POINT.setLocation(x, y);
		figure.translateFromParent(PRIVATE_POINT);
		if (!figure.getClientArea(Rectangle.SINGLETON).contains(PRIVATE_POINT)) {
			return null;
		}

		x = PRIVATE_POINT.x;
		y = PRIVATE_POINT.y;
		IFigure fig;
		IFigure result = null;
		for (int i = figure.getChildren().size(); i > 0;) {
			i--;
			fig = (IFigure) figure.getChildren().get(i);
			if (fig.isVisible()) {
				fig = fig.findFigureAt(x, y, search);
				if (fig instanceof ComboItemFigure) {
					return fig;
					// マウス動作を優先にcomboItemに取らせるために。
				} else if (result == null) {
						result = fig;
				}
			}
		}
		// Returns descendant that was found
		return result;
	}

	/**
	 * comboItemの表示対応ために
	 */
	protected void paintChildren(Graphics graphics) {

		Rectangle clip = Rectangle.SINGLETON;
		for (int i = 0; i < figure.getChildren().size(); i++) {
			IFigure child = (IFigure) figure.getChildren().get(i);
			if (child instanceof ComboFigure && child.isVisible()
					&& child.intersects(graphics.getClip(clip))) {
				if (((ComboFigure) child).isChildrenShown()) {
					
					// comboFigureのcomboItemも表示する場合、最後にこのcomboFigureを描画
					graphics.clipRect(child.getBounds());
					child.paint(graphics);
					graphics.restoreState();
				}
			}
		}
	}
}
