/*
 * 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.Bind;
import org.maskat.core.event.Target;
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 TargetChildNode extends AbstractTreeNode {
	private static final String ROW_LABEL =
		Messages.getString("sourceChildNode.rowLabel"); //$NON-NLS-1$		

	private static final String ADD_BIND_NODE =
		Messages.getString("sourceChildNode.addBindNode"); //$NON-NLS-1$
	
	public TargetChildNode(Target target) {
		super(target);
	}
	
	protected void loadChildren() {
		Iterator iterator = ((Target) maskatElement).getTypedChildren(Bind.class);
		while (iterator != null && iterator.hasNext()) {
			addChild(new TargetBind((Bind)iterator.next()));
		}
	}
	
	/**destroy the Bind 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(maskatElement == null 
			|| ((Target) maskatElement).getInkey() == null
			|| ((Target) maskatElement).getInkey().length() == 0) {
			return "<> " + ROW_LABEL;
		}
		return ((Target) maskatElement).getInkey() + " " + ROW_LABEL;
	}
	
	public IMenuManager fillContextMenu(final TreeViewer treeViewer, IMenuManager manager) {
		final ITreeNode node = this;
		manager.add(new Action(ADD_BIND_NODE){
			public void run() {
				Bind bind = new Bind();
				bind.setTokey("");
				bind.setNode("");
				ITreeNode childNode = new TargetBind(bind);
				EventPropertiesMasterDetailsBlock.executeCommand(new AddTreeNodeCommand(treeViewer,node,childNode));				
			}
		});
		return super.fillContextMenu(treeViewer, manager);
	}
}
