/* ======================================================================
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 org.bodington.applet.data.*;

import java.awt.datatransfer.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.Vector;



public class LocalFilePanel extends javax.swing.JPanel
	implements PropertyChangeListener, ClipboardOwner, FileDownloader
	{
	JSplitPane split;
	LocalFileTree tree;
	LocalFileList list;
    
    JScrollPane tree_scroll, list_scroll;
    Clipboard clipboard=null;
    
	public LocalFilePanel()
		{
	    setLayout( new GridLayout(1, 1) );

		tree = new LocalFileTree();
		tree.setShowsRootHandles( true );
		tree.setFileDownloader( this );
		tree_scroll = new JScrollPane( tree );

		tree.addPropertyChangeListener( this );
		    
		list = new LocalFileList();
		list.setFileDownloader( this );
		list_scroll = new JScrollPane( list );

		list.addPropertyChangeListener( this );

        split = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, tree_scroll, list_scroll );
        split.setDividerLocation( 250 );
        split.setOneTouchExpandable( true );
        add( split );
		}

    public void setClipboard( Clipboard clipboard )
        {
        this.clipboard = clipboard;
        }
        
	public void propertyChange(PropertyChangeEvent evt)
		{
		if ( evt.getPropertyName().equalsIgnoreCase( "leadSelectionPath" ) )
			{
			list.setDirectory( tree.getSelectedFolder() );
			}
		}
		
	public void doFileCopy()
	    {
	    if ( clipboard==null )
	        {
			JOptionPane.showMessageDialog(null, "No clipboard is available.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return;
			}
	        
	    File[] flist = list.getSelectedFiles();
	    if ( flist==null || flist.length == 0 )
	        {
			JOptionPane.showMessageDialog(null, "Select one or more files in the list box to copy it.", "Alert", JOptionPane.ERROR_MESSAGE); 
	        return;
	        }
	        
        LocalFileSelection transfer = new LocalFileSelection( flist );
     
        clipboard.setContents( transfer, this );
	    }
	    
	public boolean doFilePaste()
	    {
	    if ( clipboard==null )
	        {
			JOptionPane.showMessageDialog(null, "No clipboard is available.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return false;
			}
	    
	    Transferable data = clipboard.getContents( this );
	    if ( data == null )
	        {
			JOptionPane.showMessageDialog(null, "The clipboard is empty.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return false;
			}
			
	    if ( !data.isDataFlavorSupported( RemoteFileSelection.remoteFileSelectionFlavor ) )
	        {
    	    if ( data.isDataFlavorSupported( LocalFileSelection.localFileSelectionFlavor ) )
    			JOptionPane.showMessageDialog(null, "You can't use the clipboard to copy files within the local file system.", "Alert", JOptionPane.ERROR_MESSAGE); 
    		else
    			JOptionPane.showMessageDialog(null, "The clipboard doesn't contain files from the remote file system.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return false;
	        }

	    File target = tree.getSelectedFolder();
	    if ( target == null )
	        {
			JOptionPane.showMessageDialog(null, "Select a target folder in the tree diagram before you paste.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return false;
	        }
	        
        StringBuffer message = new StringBuffer();   
        
        RemoteFileSelection selection;
        RemoteFile[] flist;
        try
            {
            selection = (RemoteFileSelection)data.getTransferData( RemoteFileSelection.remoteFileSelectionFlavor );
            flist = selection.getFileList();
            }
        catch ( Exception ex )
            {
            ex.printStackTrace();
			JOptionPane.showMessageDialog(null, "Technical problem transferring data.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return false;
            }
         
		try
            {		    
		    transferFiles( target, flist, true );
		    }
		catch ( Exception ex )
		    {
		    ex.printStackTrace();
    		JOptionPane.showMessageDialog( null, "Technical problem transferring files.", "Alert", JOptionPane.ERROR_MESSAGE ); 
		    return false;
		    }

	
    	return true;
	    }
	    
	public void doFileProperties()
	    {
	    File[] flist = list.getSelectedFiles();
	    if ( flist==null || flist.length == 0 )
	        {
			JOptionPane.showMessageDialog(null, "Select one file in the list box to view its properties.", "Alert", JOptionPane.ERROR_MESSAGE); 
	        return;
	        }
	        
	    if ( flist.length > 1 )
	        {
			JOptionPane.showMessageDialog(null, "Select just one files in the list box to view its properties.", "Alert", JOptionPane.ERROR_MESSAGE); 
	        return;
	        }

		JOptionPane.showMessageDialog(null, "Properties functionality not implemented.", "Alert", JOptionPane.ERROR_MESSAGE); 
	    }

    public void lostOwnership( Clipboard clipboard, Transferable contents )
        {
        // don't care!
        }

	public void transferFiles( File destination, RemoteFile[] source, boolean recursive )
		throws IOException, MalformedURLException
		{
		System.out.println( "Downloading to: " + destination.getAbsolutePath() );

		if ( !destination.isDirectory() )
		    throw new IOException( "Can't download into a file." );
		    
		TransferRemoteFileDialog dialog = new TransferRemoteFileDialog( BodingtonDesktopPane.findInstance( this ) );
		dialog.setProgressListener(  BodingtonDesktopPane.findInstance( this ).getLocalFileFrame() );
		dialog.setVisible( true );
		
		Vector list = new Vector();
		transferFiles( list, destination, source, recursive );
		
		TransferRemoteFileItem[] array = new TransferRemoteFileItem[list.size()];
		for ( int i=0; i<list.size(); i++ )
		    array[i] = (TransferRemoteFileItem)list.elementAt( i );
		
		if ( !dialog.isCancelled() )
		    dialog.transfer( array );
		}
		

	private void transferFiles( Vector list, File destination, 
	                            RemoteFile[] source, boolean recursive )
		throws IOException, MalformedURLException
		{
		System.out.println( "Downloading to: " + destination );
		    
		RemoteFile[] sub_listing;
		TransferRemoteFileItem item;
		String src;
		URL src_url;
		File sub_dest;
		
		// transfer the files first
		for ( int i=0; i<source.length; i++ )
		    {
		    if ( source[i].isFile() && !source[i].isDeleted() )
			    {
			    src = source[i].getResourceUrl().toExternalForm() +
			            source[i].getPath();
			            
			    src_url = new URL( src );
    		    
			    System.out.println( "Downloading" );
			    System.out.println( src_url.toExternalForm() );
			    System.out.println( "into" );
			    System.out.println( destination.getAbsolutePath() );
    				
			    item = new TransferRemoteFileItem();
			    item.url = src_url;
			    item.file = new File( destination, source[i].getName() );
			    list.addElement( item );
			    }
			}
			
		// transfer contained files if there are any
		if ( recursive )
		    {
		    for ( int i=0; i<source.length; i++ )
		        {
		        if ( !source[i].isFile() )
		            {
		            sub_listing = source[i].list();
		            sub_dest = new File( destination, source[i].getName() );
		            if ( !sub_dest.exists() )
		                sub_dest.mkdir();
    			    transferFiles( list, sub_dest, sub_listing, recursive );
    			    }
    			}
			}

		}

	}
