package org.protege.xmlcatalog.swing;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;

import javax.swing.JComponent;
import javax.swing.TransferHandler;

import org.apache.log4j.Logger;

public class CatalogEditorTransferHandler extends TransferHandler {
	private static final long serialVersionUID = 1160492460896419035L;
	public static final Logger LOGGER = Logger.getLogger(CatalogEditorTransferHandler.class);

	public int getSourceActions(JComponent c) {
		EntryTreeNode e = getEntryTreeNode(c);
		if (e == null) {
			return NONE;
		}
		else if (e.isAutoGenerated()) {
			return COPY;
		}
		else {
			return MOVE;
		}
	}

	protected Transferable createTransferable(JComponent c) {

		final EntryTreeNode e = getEntryTreeNode(c);
		if (e == null) {
			return null;
		}
		return new Transferable() {
			
			public boolean isDataFlavorSupported(DataFlavor flavor) {
				return flavor.getRepresentationClass().equals(EntryTreeNode.class);
			}
			
			public DataFlavor[] getTransferDataFlavors() {
				return new DataFlavor[] { new DataFlavor(EntryTreeNode.class, "XML Catalog Entry")};
			}
			
			public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
				return e;
			}
		};
	}
	
	public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) {
		if (LOGGER.isDebugEnabled() && comp instanceof CatalogJTree) {
			LOGGER.debug("Last selected component " + ((CatalogJTree) comp).getLastSelectedPathComponent());
		}
		EntryTreeNode e = getEntryTreeNode(comp);
		if (e != null && (e.isAutoGenerated() || e.getEditor() != null)) {
			return false;
		}
		else if (e == null && getCatalogTreeNode(comp) == null) {
			return false;
		}
		for (DataFlavor flavor : transferFlavors)  {
			if (EntryTreeNode.class.equals(flavor.getRepresentationClass())) {
				return true;
			}
		}
		return false;
	}
	
	private EntryTreeNode getEntryTreeNode(JComponent c) {
		if (!(c instanceof CatalogJTree)) {
			return null;
		}
		CatalogJTree tree = (CatalogJTree) c;
		Object o = tree.getLastSelectedPathComponent();
		if (!(o instanceof EntryTreeNode)) {
			return null;
		}
		return (EntryTreeNode) o;
	}
	
	private CatalogTreeNode getCatalogTreeNode(JComponent c) {
		if (!(c instanceof CatalogJTree)) {
			return null;
		}
		CatalogJTree tree = (CatalogJTree) c;
		Object o = tree.getLastSelectedPathComponent();
		if (!(o instanceof CatalogTreeNode)) {
			return null;
		}
		return (CatalogTreeNode) o;
	}
}



