/*
 * 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.EditPart;
import org.eclipse.gef.GraphicalEditPart;

import org.maskat.core.MaskatElement;
import org.maskat.core.layout.TabFolder;
import org.maskat.core.layout.TabItem;
import org.maskat.ui.editors.layout.figures.TabItemFigure;
import org.maskat.ui.editors.layout.models.TabDef;

public class TabItemEditPart extends ComponentEditPart {

	protected IFigure createFigure() {
		TabItem tabItem = (TabItem) getModel();
		return new TabItemFigure(tabItem.getName());
	}

	protected List getModelChildren() {
		List result = null;
		if (getModel() instanceof MaskatElement) {
			result = ((MaskatElement) getModel()).getUnmodifiableChildren();
		}
		return (result != null) ? result : super.getModelChildren(); 
	}
	
	protected void refreshVisuals() {
		TabItem tabItem = (TabItem) getModel();
		//TabFolder tabFolderDef = (TabFolder) tabItem.getContainer();
		TabFolder tabFolder = (TabFolder) tabItem.getParent();
		
		Rectangle constraint = new Rectangle(0, 15, tabFolder.getWidth() - 1,
				tabFolder.getHeight() - 16);
		((GraphicalEditPart) getParent()).setLayoutConstraint(this, getFigure(),
				constraint);
	}

	public void propertyChange(PropertyChangeEvent evt) {
		if ("addChild".equals(evt.getPropertyName())
				|| "removeChild".equals(evt.getPropertyName())) {
			refreshChildren();
		} else if ("name".equals(evt.getPropertyName())) {
			TabItem tabItem = (TabItem) getModel();
			((TabItemFigure)getFigure()).setName(tabItem.getName());
		} else if ("title".equals(evt.getPropertyName())) {
			syncTabDefTitleWithTabItemTitle();
		}
		super.propertyChange(evt);
	}
	
	private void syncTabDefTitleWithTabItemTitle() {
		TabItem tabItem = (TabItem) getModel();
		EditPart tabFolderEditPart = getParent();
		List childrenEditPart = tabFolderEditPart.getChildren();
		for (Iterator it = childrenEditPart.iterator(); it.hasNext();) {
			EditPart childEditPart = (EditPart) it.next();
			if (childEditPart instanceof TabEditPart) {
				TabEditPart tab = (TabEditPart) childEditPart;
//				if (tabItem.getName().equals(((TabItem)tab.getModel()).getName())) {
				if (tabItem.getName().equals(((TabDef)tab.getModel()).getName())) {
//					tab.setLabel(tabItem.getTitle());
					((TabDef) tab.getModel()).setTitle(tabItem.getTitle());
//					((TabItem)tab.getModel()).setTitle(tabItem.getTitle());
					return;
				}
			}
		}
	}
}
