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

	}
