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

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.dnd.Clipboard;

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.ITreeNode;

public class PasteAction extends AbstractAction {

	private Clipboard clipboard;

	public PasteAction(TreeViewer treeViewer, Clipboard clipboard) {
		super(treeViewer);
		this.clipboard = clipboard;
	}

	public String getText() {
		return Messages.getString("paseteAction.pasteLabel"); //$NON-NLS-1$
	}
	
	public boolean isEnabled() {
		IStructuredSelection sel = (IStructuredSelection) treeViewer.getSelection();
		if (sel.size() > 1) {
			return false;
		}
		
		ITreeNode parent = (ITreeNode) sel.getFirstElement();
		ITreeNode[] children = (ITreeNode[]) clipboard.getContents(TreeNodeTransfer.getInstance());
		if (children == null || children.length <= 0) {
			return false;
		}
		
		return children[0].canPasteTo(parent) ? true : false;
	}

	public void run() {
		IStructuredSelection sel = (IStructuredSelection) treeViewer.getSelection();
		ITreeNode parent = (ITreeNode) sel.getFirstElement();

		ITreeNode[] nodes = (ITreeNode[]) clipboard.getContents(TreeNodeTransfer.getInstance());
		if (nodes == null) {
			return;
		}
		
		for (int i=0; i<nodes.length; i++) {
			EventPropertiesMasterDetailsBlock.executeCommand(new AddTreeNodeCommand(treeViewer, parent, nodes[i]));
//			parent.addChild(nodes[i]);
			
//			//set the model relation 
//			//for now, we can copy/paste TargetTreeNode,SourceTreeNode,HeaderTreeNode and BindTreeNode
//			//add their models to their parents' models' children list
//			// !!Be careful of the golbal Header!!
//			if (nodes[i] instanceof HeaderTreeNode
//				&& ((HeaderTreeNode)nodes[i]).getModel().getParent() instanceof EventDef) {
//				if (parent.getModel().getParent() instanceof EventDef) {
//					//eventDef->event
//					parent.getModel().getParent().addChild(nodes[i].getModel());
//				}else {
//					//eventDef->component->event
//					parent.getModel().getParent().getParent().addChild(nodes[i].getModel());
//				}
//			}else {
//				parent.getModel().addChild(nodes[i].getModel());
//			}
		}
		
		treeViewer.refresh(parent);
		treeViewer.setSelection(new StructuredSelection(nodes));
	}

}
