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

	}
