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

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

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

	private IFigure figure;

	private Rectangle PRIVATE_POINT = new Rectangle();

	/**
	 * 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 ComboItemLabel) {
					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();
				}
			}
		}
	}
}
