/*
 * 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.maskat.ui.Messages;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.ITreeNode;

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

public class CopyAction extends AbstractAction {

	private Clipboard clipboard;

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

	public String getText() {
		return Messages.getString("copyAction.copyLabel"); //$NON-NLS-1$
	}
	
	public boolean isEnabled() {
		IStructuredSelection sel = (IStructuredSelection) treeViewer.getSelection();
		ITreeNode[] nodes = (ITreeNode[]) sel.toList().toArray(new ITreeNode[sel.size()]);
		
		Class nodeClass = null;
		for (int i=0; nodes != null && i<nodes.length; i++) {
			if (nodeClass == null) {
				nodeClass = nodes[i].getClass();
				continue;
			}
			if (!nodes[i].getClass().equals(nodeClass)) {
				//copy doesnot suppport different node types
				return false;
			}
		}
		if (nodes != null && nodes.length > 0 && nodes[0].isCopiable()) {
			return true;
		}
		return false;
	}

	public void run() {
		IStructuredSelection sel = (IStructuredSelection) treeViewer.getSelection();
		ITreeNode[] nodes = (ITreeNode[]) sel.toList().toArray(new ITreeNode[sel.size()]);
		clipboard.setContents(new Object[] { nodes }, 
				new Transfer[] { TreeNodeTransfer.getInstance() });
	}

}
