package relational.email;

import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.io.*;
import relational.*;

/**
 * A tree that supports dragging. This lets the user dynamically
 * reshape a tree view of the current query.
 */
class DragTree
	extends JTree
	implements DragGestureListener, DragSourceListener, DropTargetListener {

	public DragTree(TreeModel tm) {
		super(tm);

		DragSource dragSource = DragSource.getDefaultDragSource();

		dragSource.createDefaultDragGestureRecognizer(
					this, // component where drag originates
					DnDConstants.ACTION_COPY_OR_MOVE, // actions
					this); // drag gesture recognizer
		
		new DropTarget(this, 
			DnDConstants.ACTION_COPY_OR_MOVE,
			this);
	}

	public String getFilename() {
		return "draggy diggery doo";
	}

	// DragGestureListener support

	public void dragGestureRecognized(DragGestureEvent e) {
		// drag anything ...
		e.startDrag(DragSource.DefaultCopyDrop, // cursor
			new StringSelection(getFilename()), // transferable
			this);  // drag source listener
	}

	// DragSourceListener support

	public void dragDropEnd(DragSourceDropEvent e) {}
	public void dragEnter(DragSourceDragEvent e) {}
	public void dragExit(DragSourceEvent e) {}
	public void dragOver(DragSourceDragEvent e) {}
	public void dropActionChanged(DragSourceDragEvent e) {}

	// DropTargetListener support
	public void drop(DropTargetDropEvent e) {
		try {
			Where where = (Where) e.getTransferable()
				.getTransferData(TransferableFilter.filterFlavor);
			e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
			WhereTreeModel wtm = ((WhereTreeModel) getModel());
			wtm.valueForPathChanged(new TreePath(wtm.getRoot()), where);
		} catch (IOException ex) {
			ex.printStackTrace();
		} catch (UnsupportedFlavorException ex) {
			System.err.println("Drop denied! "+ex);
			e.rejectDrop();
		}
//		try {
//			DataFlavor stringFlavor = DataFlavor.stringFlavor;
//
//			if(e.isDataFlavorSupported(stringFlavor)) {
//				String filename = 
//						(String)tr.getTransferData(stringFlavor);
//
//				e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
//				readFile(filename);
//				textPane.setCaretPosition(0);
//				e.dropComplete(true);
//			}
//			else {
//				e.rejectDrop();
//			}
//		}
//		catch(IOException ioe) {
//			ioe.printStackTrace();
//		}
//		catch(UnsupportedFlavorException ufe) {
//			ufe.printStackTrace();
//		}
	}
    public void dragEnter(DropTargetDragEvent e) { }
    public void dragExit(DropTargetEvent e) { }
    public void dragOver(DropTargetDragEvent e) { }
    public void dropActionChanged(DropTargetDragEvent e) { }
}
