/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

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

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 );
    			    }
    			}
			}

		}

	}
