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

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

import org.eclipse.draw2d.CompoundBorder;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.LineBorder;
import org.eclipse.draw2d.MarginBorder;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.maskat.framework.IBasicDefVisitor;
import org.maskat.framework.screendef.TreeNodeDef;
import org.maskat.framework.screendef.TreeViewDef;
import org.maskat.ide.gef.editpolicies.TreeViewEditPolicy;
import org.maskat.ide.gef.figure.MaskatLabel;

public class TreeViewEditPart extends ComponentEditPart {

	public IFigure createFigure() {
		Label label = new MaskatLabel();
		label.setBorder(new CompoundBorder(new LineBorder(), new MarginBorder(0)));

		label.setOpaque(false);
		XYLayout layout = new XYLayout();
		label.setLayoutManager(layout);
		return label;
	}

	protected List getModelChildren() {
		final List result = new ArrayList();
		TreeViewDef def = (TreeViewDef) getModel();
		TreeNodeDef treeNodeDef = (TreeNodeDef) def.getChildByTypeIdx(TreeNodeDef.class,
				0);
		// 一番目の子ノードのツリーノードしか子モデルとして扱う
		if (treeNodeDef != null) {
			result.add(treeNodeDef);
			treeNodeDef.accept(new IBasicDefVisitor() {

				public void visit(Object def) {
					result.add(def);
				}
			});
		}

		// ツリーに所属すべてのツリーノードを返す
		return result;
	}

	protected void createEditPolicies() {
		super.createEditPolicies();
		installEditPolicy(EditPolicy.LAYOUT_ROLE, new TreeViewEditPolicy());
	}

	public void propertyChange(PropertyChangeEvent evt) {
		this.refresh();
	}

	public void refresh() {
		TreeViewDef def = (TreeViewDef) getModel();
		def.iterateTree();
		super.refresh();
	}

	public void forceRefresh() {
		refresh();
		// すべての子ノードをリフレッシュ
		for (Iterator it = this.getChildren().iterator(); it.hasNext();) {
			((EditPart) it.next()).refresh();
		}
	}
}