/* ======================================================================
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 javax.swing.tree.*;
import java.beans.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;


public class MenuPanel extends javax.swing.JPanel
	implements PropertyChangeListener, ClipboardOwner
	{
	JSplitPane split;
	MenuTree tree;
	MenuItemPanel menu_item_panel;
    
    JScrollPane tree_scroll, item_scroll;

    Clipboard clipboard;

    URL resource_url;
    org.bodington.server.resources.Menu menu;
    
	public MenuPanel( URL url, org.bodington.server.resources.Menu menu )
		{
		resource_url = url;
		this.menu = menu;
		
	    setLayout( new GridLayout(1, 1) );

		tree = new MenuTree( menu );
		tree.setRootVisible( true );
		tree.setShowsRootHandles( true );
		tree_scroll = new JScrollPane( tree );

		tree.addPropertyChangeListener( this );
		    
		menu_item_panel = new MenuItemPanel();
		menu_item_panel.addPropertyChangeListener( this );
		item_scroll = new JScrollPane( menu_item_panel );

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

	
    public void setClipboard( Clipboard clipboard )
        {
        this.clipboard = clipboard;
        }

	public boolean doFileSave()
	    {
	    if ( clipboard==null )
	        {
			JOptionPane.showMessageDialog(null, "No clipboard is available.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return false;
			}
	    
		try
            {		    
            File menu_file = File.createTempFile( "menu", ".xml" );
            FileOutputStream fout = new FileOutputStream( menu_file );
            
            menu.emit( fout );
            
            fout.flush();
            fout.close();
        
		    transferMenu( menu_file );
		    }
		catch ( Exception ex )
		    {
		    ex.printStackTrace();
    		JOptionPane.showMessageDialog( null, "Technical problem transferring files.", "Alert", JOptionPane.ERROR_MESSAGE ); 
		    return false;
		    }

    	return true;
	    }
	    
	public void doFileCopy()
	    {
	    }
	    
	public void doFileProperties()
	    {
	    }

	public org.bodington.server.resources.MenuItem doNewInto()
	    {
	    org.bodington.server.resources.MenuItem target;
	    DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
	    TreePath sel = tree.getSelectionPath();
	    if ( sel == null )
	        target = (org.bodington.server.resources.MenuItem)model.getRoot();
	    else
	        target = (org.bodington.server.resources.MenuItem)sel.getLastPathComponent();
	    
	    org.bodington.server.resources.MenuItem source = 
	            new org.bodington.server.resources.MenuItem( "untitled item", null, "container", 0 );
	            
	    model.insertNodeInto( source, target, model.getChildCount( target ) );
	    
	    tree.setSelectionPath( sel.pathByAddingChild( source ) );
	    
	    return source;
	    }

	public org.bodington.server.resources.MenuItem doNewBefore()
	    {
	    return doNewBeforeOrAfter( true );
	    }
	    
	public org.bodington.server.resources.MenuItem doNewAfter()
	    {
	    return doNewBeforeOrAfter( false );
	    }
	    
	private org.bodington.server.resources.MenuItem doNewBeforeOrAfter( boolean before )
	    {
	    org.bodington.server.resources.MenuItem target, sibling;
	    DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
	    TreePath targetpath;
	    TreePath sel = tree.getSelectionPath();
	    if ( sel == null || sel.getPathCount()<2 )
	        {
	        if ( before )
    		    JOptionPane.showMessageDialog( null, "Select the item you want to a new item to appear before.", "Alert", JOptionPane.ERROR_MESSAGE ); 
    		else
    		    JOptionPane.showMessageDialog( null, "Select the item you want to a new item to appear after.", "Alert", JOptionPane.ERROR_MESSAGE ); 
		    return null;
	        }
	        
        sibling = (org.bodington.server.resources.MenuItem)sel.getLastPathComponent();
	    targetpath = sel.getParentPath();
	    target =  (org.bodington.server.resources.MenuItem)targetpath.getLastPathComponent();

	    int i = model.getIndexOfChild( target, sibling );
	    
	    org.bodington.server.resources.MenuItem source = 
	            new org.bodington.server.resources.MenuItem( "untitled item", null, "container", 0 );
	            
	    model.insertNodeInto( source, target, before?i:(i+1) );
	    
	    tree.setSelectionPath( targetpath.pathByAddingChild( source ) );
	    return source;
	    }

    private RemoteFile pasteCheck()
        {
	    if ( clipboard==null )
	        {
			JOptionPane.showMessageDialog(null, "No clipboard is available.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return null;
			}
	    
	    Transferable data = clipboard.getContents( this );
	    if ( data == null )
	        {
			JOptionPane.showMessageDialog(null, "The clipboard is empty.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return null;
			}
			
	    if ( !data.isDataFlavorSupported( RemoteFileSelection.remoteFileSelectionFlavor ) )
	        {
   			JOptionPane.showMessageDialog(null, "You can only paste a remote file here.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return null;
	        }

        
        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 null;
            }
        
        if ( flist.length != 1 )
            {
			JOptionPane.showMessageDialog(null, "You can only paste one file at a time here.", "Alert", JOptionPane.ERROR_MESSAGE); 
			return null;
            }
        
        return flist[0];
        }

    private void pasteToItem( RemoteFile file, org.bodington.server.resources.MenuItem menuitem )
        {
        menuitem.setHRef( file.getPath() );
        menuitem.setTitle( file.getName() );
		menu_item_panel.setMenuItem( tree.getSelectedMenuItem() );
        }
	
	public void doPasteInto()
	    {
	    RemoteFile rfile = pasteCheck();
	    if ( rfile == null )
	        return;
	    
	    org.bodington.server.resources.MenuItem target = 
	        doNewInto();

        pasteToItem( rfile, target );
	    }

	public void doPasteBefore()
	    {
	    RemoteFile rfile = pasteCheck();
	    if ( rfile == null )
	        return;
	    
	    org.bodington.server.resources.MenuItem target = 
	        doNewBefore();

        pasteToItem( rfile, target );
	    }
	    
	public void doPasteAfter()
	    {
	    RemoteFile rfile = pasteCheck();
	    if ( rfile == null )
	        return;
	    
	    org.bodington.server.resources.MenuItem target = 
	        doNewAfter();

        pasteToItem( rfile, target );
	    }
	    
	public void doDelete()
	    {
	    org.bodington.server.resources.MenuItem target;
	    DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
	    TreePath sel = tree.getSelectionPath();
	    TreePath parent_path;

	    if ( sel == null )
	        {
    		JOptionPane.showMessageDialog( null, "Select the item you want to delete first.", "Alert", JOptionPane.ERROR_MESSAGE ); 
    		return;
    		}

	    if ( sel.getPathCount() == 1 )
	        {
	        int i;
	        int n = model.getChildCount( model.getRoot() );
	        org.bodington.server.resources.MenuItem[] mlist = 
	            new org.bodington.server.resources.MenuItem[n];
	        for ( i=0; i<n; i++ )
	            mlist[i] = (org.bodington.server.resources.MenuItem)
	                model.getChild( model.getRoot(), i );
	        for ( i=0; i<n; i++ )
	            model.removeNodeFromParent( mlist[i] );
    		}
        else
            {
            target = (org.bodington.server.resources.MenuItem)sel.getLastPathComponent();
            parent_path = sel.getParentPath();
	        model.removeNodeFromParent( target );
    	    tree.setSelectionPath( parent_path );
	        }
	    }


	
	
	public void propertyChange( PropertyChangeEvent evt )
		{
		System.err.println( evt.getPropertyName() );

		if ( evt.getSource() == tree && 
		     evt.getPropertyName().equalsIgnoreCase( "leadSelectionPath" ) )
			{
			menu_item_panel.setMenuItem( tree.getSelectedMenuItem() );
			}

		if ( evt.getSource() == menu_item_panel &&
		     evt.getPropertyName().equalsIgnoreCase( "MenuItem" ) )
		    {
		    tree.repaint();
		    }
		}

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

	private void transferMenu( File source )
		throws IOException, MalformedURLException
		{
		System.out.println( "Uploading menu: " );
		TransferLocalFileDialog dialog = new TransferLocalFileDialog( BodingtonDesktopPane.findInstance( this ) );

		String dest;
		
		dest = resource_url.toExternalForm() +
			    "bs_virtual_menuconfirm.txt";
			            
		URL publish_page_url = new URL(	dest );
    		    
		System.out.println( "Uploading" );
		System.out.println( source.getAbsolutePath() );
		System.out.println( "to" );
		System.out.println( publish_page_url.toExternalForm() );
    				
		dialog.transfer( source, null, publish_page_url );
			
		}

	}
