/*
 * 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.editparts;

import java.beans.PropertyChangeEvent;
import java.util.Iterator;
import java.util.List;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.editparts.AbstractGraphicalEditPart;

import org.maskat.core.MaskatElement;
import org.maskat.core.layout.Grid;
import org.maskat.core.layout.Component;
import org.maskat.ui.editors.layout.figures.GridFigure;

public class GridEditPart extends ComponentEditPart implements VerticalResizable {

	protected IFigure createFigure() {
		return new GridFigure((Grid) getModel());
	}

	public void propertyChange(PropertyChangeEvent evt) {
		if ("text".equals(evt.getPropertyName())) {
			getFigure().repaint();
		} else 	if ("gridHeaderTitle".equals(evt.getPropertyName())
						|| "gridHeaderWidth".equals(evt.getPropertyName())
						|| "lineHeight".equals(evt.getPropertyName())) {
			for (Iterator it = this.getChildren().iterator(); it != null
				&& it.hasNext();) {
				((AbstractGraphicalEditPart) it.next()).refresh();
			}
			getFigure().repaint();
		} else 	if ("addChild".equals(evt.getPropertyName())
					|| "removeChild".equals(evt.getPropertyName())) {
			refresh();
			for (Iterator it = this.getChildren().iterator(); it != null
					&& it.hasNext();) {
				((AbstractGraphicalEditPart) it.next()).refresh();
			}
			this.getFigure().repaint();
		}
//		refreshVisuals();
		super.propertyChange(evt);
	}

	protected List getModelChildren() {
		List result = null;
		if (getModel() instanceof MaskatElement) {
			result = ((MaskatElement) getModel()).getUnmodifiableChildren();
		}
		if (result != null) {
			return result;
		}
		return super.getModelChildren();
	}
	
	protected void refreshVisuals() {
		Component comp = (Component) getModel();
		
		int tableWidth = ((Grid) comp).headerTotalWidth();
		if (tableWidth <= 0)
			tableWidth = 100;// テーブルのデフォルト幅
		Rectangle constraint = new Rectangle(comp.getLeft(),
					comp.getTop(), tableWidth, comp.getHeight());
		
		((GraphicalEditPart) getParent()).setLayoutConstraint(this, getFigure(), constraint);
	}
}
