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

import org.eclipse.gef.commands.Command;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.maskat.ui.views.properties.tabbed.masterdetails.EventPropertiesMasterDetailsBlock;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.ITreeNode;

public class AddTreeNodeCommand extends Command {
	
	private TreeViewer treeViewer;
	
	private ITreeNode parentTreeNode;
	
	private ITreeNode childToBeAddedTreeNode;

	public AddTreeNodeCommand(TreeViewer treeViewer, ITreeNode parentTreeNode, ITreeNode childToBeAddedTreeNode) {
		super();
		this.treeViewer = treeViewer;
		this.parentTreeNode = parentTreeNode;
		this.childToBeAddedTreeNode = childToBeAddedTreeNode;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#canUndo()
	 */
	public boolean canUndo() {
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#execute()
	 */
	public void execute() {
		try {
			parentTreeNode.addChild(childToBeAddedTreeNode);
			treeViewer.refresh(parentTreeNode, true);
			treeViewer.setSelection(new StructuredSelection(childToBeAddedTreeNode),true);
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.commands.Command#undo()
	 */
	public void undo() {
		
		try {
			// the treeNode may be recreated after refresh the treeview.
			// so let's get the new treenode
			ITreeNode newParentTreeNode = EventPropertiesMasterDetailsBlock.getTreeNode(
					parentTreeNode.getModel(), parentTreeNode.getClass());
			parentTreeNode = newParentTreeNode == null ? parentTreeNode : newParentTreeNode;
			ITreeNode newChildToBeAddedTreeNode = EventPropertiesMasterDetailsBlock.getTreeNode(
					childToBeAddedTreeNode.getModel(), childToBeAddedTreeNode.getClass());
			childToBeAddedTreeNode = newChildToBeAddedTreeNode == null ? childToBeAddedTreeNode : newChildToBeAddedTreeNode;
			parentTreeNode.removeChild(childToBeAddedTreeNode);
			treeViewer.refresh(parentTreeNode, true);
			treeViewer.setSelection(new StructuredSelection(parentTreeNode));
		} catch (Exception e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
		}
	}

}
