/* ======================================================================
The Bodington System Software License, Version 1.0
  
Copyright (c) 2001 The University of Leeds.  All rights reserved.
  
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1.  Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

2.  Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3.  The end-user documentation included with the redistribution, if any,
must include the following acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES 
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO 
EVENT SHALL THE UNIVERSITY OF LEEDS OR ITS CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
=========================================================

This software was originally created by the University of Leeds and may contain voluntary 
contributions from others.  For more information on the Bodington Open Source Project, please 
see http://bodington.org/

====================================================================== */

package org.bodington.applet.components;

import org.bodington.applet.*;
import javax.swing.*;

import java.awt.dnd.*;
import java.beans.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
import javax.swing.tree.*;
import org.bodington.server.ims.*;

public class PackageFileTree extends javax.swing.JTree 
    implements java.awt.dnd.DragGestureListener, 
                java.awt.dnd.DragSourceListener, 
                java.awt.dnd.DropTargetListener
    {
  /**
   * enables this component to be a dropTarget
   */

  DropTarget dropTarget = null;

  /**
   * enables this component to be a Drag Source
   */
  DragSource dragSource = null;

	String publish_base, publish_page;

	public PackageFileTree()
		{
		dropTarget = new DropTarget (this, this);
		dragSource = new DragSource();
		dragSource.createDefaultDragGestureRecognizer( this, DnDConstants.ACTION_COPY_OR_MOVE, this);

          setRootVisible( false );
          setShowsRootHandles( true );
		}

	public PackageFileTree( TreeModel model, String publish_base, String publish_page )
	    {
	    this();
	    setModel( model );
	    this.publish_base = publish_base;
	    this.publish_page = publish_page;
	    }


    public void dragDropEnd(DragSourceDropEvent dsde)
    {
        // This method is derived from interface java.awt.dnd.DragSourceListener
        // to do: code goes here
    }

    public void dragEnter(DropTargetDragEvent dtde)
        {
        System.out.println( "public void dragEnter(DropTargetDragEvent dtde)" );
        dtde.acceptDrag( DnDConstants.ACTION_COPY );
        }

    public void dragEnter(DragSourceDragEvent dsde)
    {
        // This method is derived from interface java.awt.dnd.DragSourceListener
        // to do: code goes here
    }

    public void dragExit(DropTargetEvent dte)
    {
        // This method is derived from interface java.awt.dnd.DropTargetListener
        // to do: code goes here
    }

    public void dragExit(DragSourceEvent dse)
    {
        // This method is derived from interface java.awt.dnd.DragSourceListener
        // to do: code goes here
    }

    public void dragGestureRecognized(DragGestureEvent event)
    {
    Point p = event.getDragOrigin();
	 TreePath sourcepath = getPathForLocation( p.x, p.y );
	 PackageFileSystemNode sourcenode;
	 PackageFile pf;
	 PackageResource res;
	 
    if ( sourcepath != null )
   	{
		sourcenode = (PackageFileSystemNode)sourcepath.getLastPathComponent();
		pf = sourcenode.getPackageFile();
        if ( pf != null )
            {
            res = (PackageResource)pf.getParent();
            if ( res.getHref().equals( pf.getHref() ) )
                {
                System.out.println( "Starting drag..." );
                dragSource.startDrag(event, DragSource.DefaultMoveDrop, (Transferable)res, this);
                }
            }
   	}
   else
   	{
      System.out.println( "nothing was selected");   
   	}
    }

    public void dragOver(DragSourceDragEvent dsde)
    {
        // This method is derived from interface java.awt.dnd.DragSourceListener
        // to do: code goes here
    }

    public void dragOver(DropTargetDragEvent dtde)
        {
        dtde.acceptDrag(DnDConstants.ACTION_COPY);
        // This method is derived from interface java.awt.dnd.DropTargetListener
        // to do: code goes here
        }

		public void transferTree( TransferLocalFileDialog dialog, File base, File publish )
			throws IOException, MalformedURLException
			{
			// transfer the file first, if it is a file
			if ( publish.isFile() )
				{
				String base_abs = base.getAbsolutePath();
				String publish_abs = publish.getAbsoluteFile().getParent();
				
				if ( base_abs.length() > publish_abs.length() )
					throw new IOException( "Can't upload file outside of selected package folder." );

				String relative;	
				
				if ( base_abs.length() < publish_abs.length() )
					relative = URLEncoder.encode( publish_abs.substring( base_abs.length()+1 ) ) + "/";
				else
					relative = "";
					
				System.out.println( "Relative destination folder on server: " + relative );
				System.out.println( "Absolute base URL: " + publish_base );
				
				URL publish_page_url = new URL(	publish_base + relative + publish_page   );
				
				System.out.println( "Uploading" );
				System.out.println( publish.getAbsolutePath() );
				System.out.println( "to" );
				System.out.println( publish_page_url.toExternalForm() );
				
				dialog.transfer( publish, null, publish_page_url );
				}
			
			// transfer contained file if there are any
			File[] filelist = publish.listFiles();
			for ( int i=0; filelist!=null && i<filelist.length; i++ )
				transferTree( dialog, base, filelist[i] );

			}
			
    public void drop(DropTargetDropEvent event)
        {
	System.out.println( "Drop requested" );

	try
		{
		Transferable transferable = event.getTransferable();
		Point p = event.getLocation();
		TreePath targetpath;
		Rectangle targetbox;
		PackageFile targetnode;
		DefaultTreeModel model = (DefaultTreeModel)getModel();
		int position;


		
		// we accept only    FilePublishRequest.filePublishRequestFlavor
		if (transferable.isDataFlavorSupported( FilePublishRequest.filePublishRequestFlavor ) )
			{
			System.out.println( "FilePublishRequest dropped" );
			FilePublishRequest request =(FilePublishRequest)transferable.getTransferData( 
																FilePublishRequest.filePublishRequestFlavor );
			
			if ( !request.publish.exists() )
				{
				System.out.println( "Dragged file doesn't exist." );
				event.rejectDrop();
				return;
				}

			event.acceptDrop( DnDConstants.ACTION_COPY );

			try
				{
				System.out.println( "Uploading " + request.publish );
				TransferLocalFileDialog t_dialog = new TransferLocalFileDialog( BodingtonDesktopPane.findInstance( this ) );
				
				// recursively publish stuff
				transferTree( t_dialog, request.base, request.publish );
				}
			catch ( Exception ex )
				{
				ex.printStackTrace();
				}

			event.getDropTargetContext().dropComplete(true);
			return;
			}
		
		System.out.println( "Drop rejected" );
		event.rejectDrop();
		}
	catch (IOException exception)
		{
		exception.printStackTrace();
		System.err.println( "Exception" + exception.getMessage());
		event.rejectDrop();
		} 
	catch (UnsupportedFlavorException ufException )
		{
		ufException.printStackTrace();
		System.err.println( "Exception" + ufException.getMessage());
		event.rejectDrop();
		}   
   }

    public void dropActionChanged(DragSourceDragEvent dsde)
    {
        // This method is derived from interface java.awt.dnd.DragSourceListener
        // to do: code goes here
    }

    public void dropActionChanged(DropTargetDragEvent dtde)
    {
        // This method is derived from interface java.awt.dnd.DropTargetListener
        // to do: code goes here
    }

}
