/* ======================================================================
   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 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 );
			
		}

	}
