/*
 * 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.views.properties.tabbed.beanwrapper;

import java.util.Iterator;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.viewers.TreeViewer;

import org.maskat.core.event.Param;
import org.maskat.core.event.Source;
import org.maskat.ui.Messages;
import org.maskat.ui.views.properties.tabbed.command.AddTreeNodeCommand;
import org.maskat.ui.views.properties.tabbed.masterdetails.EventPropertiesMasterDetailsBlock;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.AbstractTreeNode;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.ITreeNode;

public class ParamTreeNode extends AbstractTreeNode {

	private static final String ROOT_NODE_LABEL =
		Messages.getString("paramTreeNode.rootNodeLabel"); //$NON-NLS-1$		

	private static final String ADD_SOUCE_NODE =
		Messages.getString("paramTreeNode.addSourceNode"); //$NON-NLS-1$

	public ParamTreeNode(Param param) {
		super(param);
	}

	protected void loadChildren() {
		Iterator iterator = ((Param) maskatElement).getTypedChildren(Source.class);
		while (iterator!=null && iterator.hasNext()) {
			addChild(new SourceNode((Source)iterator.next()));
		}
	}
	
	/**destroy the Source bean of the child after remove the child*/
	public void removeChild(ITreeNode child) {
		super.removeChild(child);
		maskatElement.removeChild(child.getModel());
	}
	
	/**add the model relation when add child*/
	public void addChild(ITreeNode child) {
		super.addChild(child);
		maskatElement.addChild(child.getModel());
	}
	
	public String getDisplayText() {
		if (((Param)maskatElement).getRootNode() == null
			|| ((Param)maskatElement).getRootNode().length() == 0) {
			return ROOT_NODE_LABEL;
		}
		Param param = (Param) maskatElement;
		return param.getRootNode() + " " + ROOT_NODE_LABEL;
	}
	
	public IMenuManager fillContextMenu(final TreeViewer treeViewer, IMenuManager manager) {
		final ITreeNode node = this;
		manager.add(new Action(ADD_SOUCE_NODE){
			public void run() {
				Source source = new Source();
				source.setNode("");
				ITreeNode childNode = new SourceNode(source);
				EventPropertiesMasterDetailsBlock.executeCommand(new AddTreeNodeCommand(treeViewer,node,childNode));				
			}
		});
		return super.fillContextMenu(treeViewer, manager);
	}
}
