/* ======================================================================
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 org.bodington.server.resources.*;
import org.bodington.xml.XMLUtils;

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.*;  
import org.xml.sax.helpers.*;
import org.w3c.dom.*;


public class MenuFrame extends javax.swing.JInternalFrame
    implements ActionListener
	{
	
	MenuPanel panel;
	URL resource_base;
	org.bodington.server.resources.Menu menu;

    JMenuBar menu_bar;
    JMenu file_menu, edit_menu, view_menu;
    
    JMenu edit_new_sub_menu, edit_paste_sub_menu;
    
    JMenuItem   save_menu_item, copy_menu_item, cut_menu_item, 
                properties_menu_item;
                
    JMenuItem   new_into_menu_item,
                new_before_menu_item,
                new_after_menu_item,
                paste_into_menu_item,
                paste_before_menu_item,
                paste_after_menu_item,
                delete_menu_item;
    
    JMenuItem   refresh_menu_item;
    
	Clipboard clipboard;
	
	
	public MenuFrame( URL url )
		{
		super( "Menus in Bodington", true, false, true, true );

        // menu items on menu bar
        save_menu_item  = new JMenuItem( "Save As Custom Menu", 'S' );
        copy_menu_item  = new JMenuItem( "Copy", 'C' );
        cut_menu_item  = new JMenuItem( "Cut", 'T' );
        properties_menu_item  = new JMenuItem( "Properties", 'P' );
        
        
        new_before_menu_item = new JMenuItem( "Before", 'B' );
        new_into_menu_item  = new JMenuItem( "In", 'I' );
        new_after_menu_item = new JMenuItem( "After", 'A' );
        
        paste_before_menu_item = new JMenuItem( "Before", 'B' );
        paste_into_menu_item  = new JMenuItem( "In", 'I' );
        paste_after_menu_item = new JMenuItem( "After", 'A' );
        
        delete_menu_item = new JMenuItem( "Delete", 'D' );
        
        refresh_menu_item  = new JMenuItem( "Refresh", 'R' );

        save_menu_item.addActionListener( this );
        copy_menu_item.addActionListener( this );
        cut_menu_item.addActionListener( this );
        properties_menu_item.addActionListener( this );
        new_before_menu_item.addActionListener( this );
        new_into_menu_item.addActionListener( this );
        new_after_menu_item.addActionListener( this );
        paste_before_menu_item.addActionListener( this );
        paste_into_menu_item.addActionListener( this );
        paste_after_menu_item.addActionListener( this );
        delete_menu_item.addActionListener( this );
        refresh_menu_item.addActionListener( this );
        
        edit_new_sub_menu = new JMenu( "New Item" );
        edit_new_sub_menu.add( new_before_menu_item );
        edit_new_sub_menu.add( new_into_menu_item );
        edit_new_sub_menu.add( new_after_menu_item );
        
        edit_paste_sub_menu = new JMenu( "Paste" );
        edit_paste_sub_menu.add( paste_before_menu_item );
        edit_paste_sub_menu.add( paste_into_menu_item );
        edit_paste_sub_menu.add( paste_after_menu_item );
        
        file_menu = new JMenu( "File" );
        file_menu.add( save_menu_item );
        //file_menu.addSeparator();
        //file_menu.add( copy_menu_item );
        //file_menu.add( cut_menu_item );
        //file_menu.addSeparator();
        //file_menu.add( properties_menu_item );

        edit_menu = new JMenu( "Edit" );
        edit_menu.add( edit_new_sub_menu );
        edit_menu.add( edit_paste_sub_menu );
        edit_menu.add( delete_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() == save_menu_item )
            {
            panel.doFileSave();
            }
        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() == properties_menu_item )
            {
            panel.doFileProperties();
            }
        else if ( e.getSource() == new_before_menu_item )
            {
            panel.doNewBefore();
            }
        else if ( e.getSource() == new_into_menu_item )
            {
            panel.doNewInto();
            }
        else if ( e.getSource() == new_after_menu_item )
            {
            panel.doNewAfter();
            }
        else if ( e.getSource() == paste_before_menu_item )
            {
            panel.doPasteBefore();
            }
        else if ( e.getSource() == paste_into_menu_item )
            {
            panel.doPasteInto();
            }
        else if ( e.getSource() == paste_after_menu_item )
            {
            panel.doPasteAfter();
            }
        else if ( e.getSource() == delete_menu_item )
            {
            panel.doDelete();
            }
        else if ( e.getSource() == refresh_menu_item )
            {
            doRefresh();
            }
        }
        
    public void doRefresh()
        {
        if ( panel!=null )
	    getContentPane().remove( panel );
        loadMenu();
   	panel = new MenuPanel( resource_base, menu );
        panel.setClipboard( clipboard );
    	getContentPane().add( panel );
	getContentPane().validate();
        }
	
	public org.bodington.server.resources.Menu loadMenu()
	    {
        URL u=null;
		InputStream in=null;
			
	    menu = null;
	    
	    if ( resource_base == null )
	        return null;
	    
        try
            {
           	LoginDialog dialog = new LoginDialog();
           	dialog.setModal( true );
            	
            u = new URL( resource_base, "bs_generated_menu.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;
	            }

      	    MenuHandler mhandler = new MenuHandler();
            XMLReader reader=null;
   			try
   				{
      	        reader = XMLReaderFactory.createXMLReader(XMLUtils.getXMLReader());
   				}
   			catch ( Throwable th )
   				{
   				th.printStackTrace();
            	JOptionPane.showMessageDialog(null, "Couldn't find XML parser to process file listing.", "Alert", JOptionPane.ERROR_MESSAGE); 
	            return null;
   				}
   		
            InputSource source = new InputSource( in );
            source.setEncoding( "utf-8" );
      	    reader.setContentHandler( mhandler );
      	    reader.parse( source );
      	    
		    menu = mhandler.getMenu();
   		
			return menu;
        	}
        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 ( 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;

	//{{DECLARE_CONTROLS
	//}}
	

	}
