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

import javax.xml.parsers.DocumentBuilderFactory;  
import javax.xml.parsers.FactoryConfigurationError;  
import javax.xml.parsers.ParserConfigurationException;
 
import javax.xml.parsers.DocumentBuilder;  
import org.xml.sax.SAXException;  
import org.xml.sax.SAXParseException;  
import org.w3c.dom.*;


public class RemoteFileFrame extends javax.swing.JInternalFrame
    implements ActionListener, ProgressListener
	{
	
	RemoteFilePanel panel;
	URL resource_base;
	RemoteFile root;

    JMenuBar menu_bar;

    JMenu file_menu, edit_menu, view_menu;
    
    JMenu new_file_sub_menu, open_with_sub_menu;
    
    JMenuItem   open_with_text_editor_menu_item,
                rename_file_menu_item,
		delete_file_menu_item,
		undelete_file_menu_item,
                new_folder_menu_item,
                new_text_file_menu_item,
                new_html_file_menu_item,
                copy_menu_item, cut_menu_item, 
                paste_menu_item, properties_menu_item,
                refresh_menu_item;
    
	Clipboard clipboard;
	

	// Reference to the Menu editing frame so that this frame
	// can tell it to update when published files are updated.
	MenuFrame menu_frame=null;
	
	
	public RemoteFileFrame( URL url )
		{
		super( "Files on Bodington", true, false, true, true );

        open_with_text_editor_menu_item = new JMenuItem( "Text Editor", 'T' );
        
        new_folder_menu_item = new JMenuItem( "Folder", 'F' );
        new_text_file_menu_item = new JMenuItem( "Plain Text File", 'T' );
        new_html_file_menu_item = new JMenuItem( "HTML File", 'H' );
	delete_file_menu_item = new JMenuItem( "Delete", 'D' );
	undelete_file_menu_item = new JMenuItem( "Undelete", 'U' );
        rename_file_menu_item = new JMenuItem( "Rename", 'R' );
        properties_menu_item  = new JMenuItem( "Properties", 'P' );

        copy_menu_item  = new JMenuItem( "Copy", 'C' );
        cut_menu_item  = new JMenuItem( "Cut", 'T' );
        paste_menu_item  = new JMenuItem( "Paste", 'P' );

        refresh_menu_item  = new JMenuItem( "Refresh", 'R' );

        open_with_text_editor_menu_item.addActionListener( this );
        new_folder_menu_item.addActionListener( this );
        new_text_file_menu_item.addActionListener( this );
        new_html_file_menu_item.addActionListener( this );
        delete_file_menu_item.addActionListener( this );
        undelete_file_menu_item.addActionListener( this );
        rename_file_menu_item.addActionListener( this );
        copy_menu_item.addActionListener( this );
        cut_menu_item.addActionListener( this );
        paste_menu_item.addActionListener( this );
        properties_menu_item.addActionListener( this );
        refresh_menu_item.addActionListener( this );
        
        new_file_sub_menu = new JMenu( "New" );
        new_file_sub_menu.add( new_folder_menu_item );
        new_file_sub_menu.add( new_text_file_menu_item );
        new_file_sub_menu.add( new_html_file_menu_item );
        
        open_with_sub_menu = new JMenu( "Open With" );
        open_with_sub_menu.add( open_with_text_editor_menu_item );

        file_menu = new JMenu( "File" );
        file_menu.add( new_file_sub_menu );
        file_menu.addSeparator();
        file_menu.add( open_with_sub_menu );
        file_menu.add( rename_file_menu_item );
        file_menu.add( properties_menu_item );
        file_menu.addSeparator();
        file_menu.add( delete_file_menu_item );
        file_menu.add( undelete_file_menu_item );
        
        edit_menu = new JMenu( "Edit" );
        edit_menu.add( copy_menu_item );
        edit_menu.add( cut_menu_item );
        edit_menu.add( paste_menu_item );

        view_menu = new JMenu( "View" );
        view_menu.add( refresh_menu_item );

        menu_bar = new JMenuBar();
        menu_bar.add( file_menu );
        menu_bar.add( edit_menu );
        menu_bar.add( view_menu );
        
        setJMenuBar( menu_bar );

        resource_base = url;
        
        doRefresh();
		}

    public void setClipboard( Clipboard clipboard )
        {
        this.clipboard = clipboard;
        panel.setClipboard( clipboard );
        }
        
    public void actionPerformed(ActionEvent e)
        {
        System.out.println( "LocalFileFrame action performed" );

        if ( e.getSource() == open_with_text_editor_menu_item )
            {
            panel.doOpenTextFile();
            }
        else if ( e.getSource() == new_folder_menu_item )
            {
            panel.doNewFolder();
            doRefresh();
            }
        else if ( e.getSource() == new_text_file_menu_item )
            {
            panel.doNewFile( "text/plain" );
            doRefresh();
            }
        else if ( e.getSource() == new_html_file_menu_item )
            {
            panel.doNewFile( "text/html" );
            doRefresh();
            }
        else if ( e.getSource() == rename_file_menu_item )
            {
            panel.doRename();
            doRefresh();
            }
        else if ( e.getSource() == delete_file_menu_item )
            {
            panel.doDelete();
            doRefresh();
            }
        else if ( e.getSource() == undelete_file_menu_item )
            {
            panel.doUndelete();
            doRefresh();
            }
        else if ( e.getSource() == cut_menu_item )
            {
          	JOptionPane.showMessageDialog(null, "Cut functionality not yet imlemented.", "Alert", JOptionPane.ERROR_MESSAGE); 
            }
        else if ( e.getSource() == copy_menu_item )
            {
            panel.doFileCopy();
            }
        else if ( e.getSource() == paste_menu_item )
            {
            if ( panel.doFilePaste() )
                doRefresh();
            }
        else if ( e.getSource() == properties_menu_item )
            {
            panel.doFileProperties();
            }
        else if ( e.getSource() == refresh_menu_item )
            {
            doRefresh();
            }
        }
        
    public void progressCompleted( ProgressDialog dialog, boolean error )
	{
            try { Thread.sleep( 1000 ); } catch ( InterruptedException e ) {}
            doRefresh();
	}
	    
    public synchronized void doRefresh()
        {
	getContentPane().removeAll();
        loadResourceRoot();
   		panel = new RemoteFilePanel( resource_base, root );
        panel.setClipboard( clipboard );
    	getContentPane().add( panel );
	getContentPane().validate();
	// if published files are changed then the menu is changed too.
	if ( menu_frame != null )
	    menu_frame.doRefresh();
        }
	
	public RemoteFile loadResourceRoot()
	    {
        URL u=null;
		InputStream in=null;
   		Document document = null;
			
	    root = null;
	    
	    if ( resource_base == null )
	        return null;
	    
        try
            {
           	LoginDialog dialog = new LoginDialog();
           	dialog.setModal( true );
            	
            	
            u = new URL( resource_base, "bs_generated_filelisting.xml" );    // add data to the source List
            URLConnection connect = u.openConnection();
                
            if ( !dialog.login( connect ) )
            	{
            	JOptionPane.showMessageDialog(null, "Can't fetch remote file listing because login failed.", "Alert", JOptionPane.ERROR_MESSAGE); 
            	return null;
            	}
            		
                
            in = connect.getInputStream();
            if ( in == null )
            	{
            	JOptionPane.showMessageDialog(null, "Failed to retreive remote file listing.", "Alert", JOptionPane.ERROR_MESSAGE); 
	            return null;
	            }

   			try
   				{
   				Class.forName( "javax.xml.parsers.DocumentBuilderFactory" );
   				}
   			catch ( Throwable th )
   				{
   				th.printStackTrace();
            	JOptionPane.showMessageDialog(null, "Couldn't find XML parser to process file listing.", "Alert", JOptionPane.ERROR_MESSAGE); 
	            return null;
   				}
   		
   			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder builder = factory.newDocumentBuilder();
        	document = builder.parse( in );
			
			root = new RemoteFile( document, resource_base );
			return root;
        	}
        catch (SAXParseException spe)
        	{
			// Error generated by the parser
			System.out.println ("\n** Parsing error" 
    			+ ", line " + spe.getLineNumber ()
    			+ ", uri " + spe.getSystemId ());
			System.out.println("   " + spe.getMessage() );

			// Use the contained exception, if any
			Exception  x = spe;
			if (spe.getException() != null)
    			x = spe.getException();
			x.printStackTrace();

			JOptionPane.showMessageDialog(null, "Couldn't parse XML.", "Alert", JOptionPane.ERROR_MESSAGE); 
        	}
        catch (SAXException sxe)
        	{
			// Error generated by this application
			// (or a parser-initialization error)
			Exception  x = sxe;
			if (sxe.getException() != null)
    			x = sxe.getException();
			x.printStackTrace();

			JOptionPane.showMessageDialog(null, "Couldn't parse XML.", "Alert", JOptionPane.ERROR_MESSAGE); 
        	}
        catch (ParserConfigurationException pce)
        	{
            // Parser with specified options can't be built
            pce.printStackTrace();

			JOptionPane.showMessageDialog(null, "Couldn't parse XML.", "Alert", JOptionPane.ERROR_MESSAGE); 
	        } 
        catch ( MalformedURLException uex )
            {
            uex.printStackTrace();
           	JOptionPane.showMessageDialog(null, "Invalid URL to resource.", "Alert", JOptionPane.ERROR_MESSAGE); 
            }
        catch ( Exception ex )
            {
            ex.printStackTrace();
           	JOptionPane.showMessageDialog(null, "Problem getting data.", "Alert", JOptionPane.ERROR_MESSAGE); 
            }
		
        return null;		
	    }
	

	public void addNotify()
		{
		// Record the size of the window prior to calling parents addNotify.
		Dimension d = getSize();

		super.addNotify();

		if (fComponentsAdjusted)
			return;

		// Adjust components according to the insets
		Insets ins = getInsets();
		setSize(ins.left + ins.right + d.width, ins.top + ins.bottom + d.height);
		Component components[] = getContentPane().getComponents();
		for (int i = 0; i < components.length; i++)
			{
			Point p = components[i].getLocation();
			p.translate(ins.left, ins.top);
			components[i].setLocation(p);
		}
		fComponentsAdjusted = true;
		}

	// Used for addNotify check.
	boolean fComponentsAdjusted = false;


	public void setMenuFrame( MenuFrame mframe )
	    {
	    menu_frame = mframe;
	    }

	}
