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


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.bodington.applet.data.*;
import org.bodington.server.ims.*;
import org.w3c.dom.*;

public class PackageEditFrame extends javax.swing.JInternalFrame
    implements MenuListener, ActionListener
    {
    PackageEditPanel panel;
    JMenuItem   save_menu_item, 
                file_delete_menu_item,
                file_rename_menu_item,
                prop_menu_item,
                exit_menu_item, 
                view_local_files_menu_item,
                view_remote_files_menu_item,
                local_manifest_menu_item;
                
    JMenuBar menu_bar;
    JMenu file_menu, view_menu;
		JFileChooser file_chooser=null;
  	
  	Document doc;
	
	URL res_base;

	public PackageEditFrame( URL res_base )
	    {
	    super( "Package Manifest", true, false, true, true );
	    setLocation( 100, 100 );
	    setSize( 300, 200 );

		this.res_base = res_base;
		
	    panel = new PackageEditPanel();

	    getContentPane().setLayout( new GridLayout(1, 1) );
        getContentPane().add( panel );

        save_menu_item  = new JMenuItem( "Save", 'S' );
        file_delete_menu_item  = new JMenuItem( "Delete", 'D' );
        file_rename_menu_item  = new JMenuItem( "Rename", 'R' );
        prop_menu_item  = new JMenuItem( "Properties", 'P' );
        exit_menu_item  = new JMenuItem( "Exit", 'x' );
        
        view_local_files_menu_item = new JMenuItem( "Local Files", 'L' );
        view_remote_files_menu_item = new JMenuItem( "Remote Files", 'R' );
        
        save_menu_item.addActionListener( this );
        file_delete_menu_item.addActionListener( this );
        file_rename_menu_item.addActionListener( this );
        prop_menu_item.addActionListener( this );
        exit_menu_item.addActionListener( this );
        
        view_local_files_menu_item.addActionListener( this );
        view_remote_files_menu_item.addActionListener( this );
        
        file_menu = new JMenu( "File" );
        file_menu.add( save_menu_item );
        file_menu.addSeparator();
        file_menu.add( file_delete_menu_item );
        file_menu.add( file_rename_menu_item );
        file_menu.add( prop_menu_item );
        file_menu.addSeparator();
        file_menu.add( exit_menu_item );
        file_menu.addMenuListener( this );
        
        view_menu = new JMenu( "View" );
        view_menu.add( view_local_files_menu_item );
        view_menu.add( view_remote_files_menu_item );
        view_menu.addMenuListener( this );
        
        menu_bar = new JMenuBar();
        menu_bar.add( file_menu );
        menu_bar.add( view_menu );
        
        setJMenuBar( menu_bar );
    	}

	    
	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 setUploadURL( URL url )
		{
		panel.setUploadURL( url );
		}


	public void setManifest( InputStream manifest )
		{
		panel.setManifest( manifest );
		}
  
    public void menuCanceled(MenuEvent e)
        {
        }
    public void menuDeselected(MenuEvent e)
        {
        }
    public void menuSelected(MenuEvent e)
        {
        JMenuItem item = (JMenuItem)e.getSource();
        System.out.println( item.getText() );
        
        if ( item == file_menu )
            {
                {
                save_menu_item.setEnabled( false );
                file_delete_menu_item.setEnabled( true );
                file_rename_menu_item.setEnabled( true );
                prop_menu_item.setEnabled( true );
                exit_menu_item.setEnabled( true );
                }
            }
        else if ( item == view_menu )
            {
            view_local_files_menu_item.setEnabled( true );
            view_remote_files_menu_item.setEnabled( true );
            }
        }
        
    public void actionPerformed(ActionEvent e)
        {
        if ( e.getSource() == exit_menu_item )
            {
            this.setVisible( false );
            return;
            }

        if ( e.getSource() == save_menu_item )
            {
            panel.doSave();
            return;
            }
        }

	private class ManifestFileFilter extends FileFilter
		{
		public boolean accept(File f)
			{
			return f.isDirectory() || f.getName().equalsIgnoreCase( "imsmanifest.xml" );
			}
			
		public String getDescription()
			{
			return "IMS Package Manifests";
			}
		}

   
    private class CreateLocalManifestButton extends JButton
   	implements PropertyChangeListener, ActionListener
   	{
   	public CreateLocalManifestButton()
   		{
   		super( "Create Manifest File Here" );
      	file_chooser.addPropertyChangeListener(this);
      	addActionListener( this );
			enableAsAppropriate();
			setPreferredSize( new Dimension( 150, 25 ) );
			//setSize( getMinimumSize() );
        }
       
    public void enableAsAppropriate()
   	{
		System.out.println( "Enable as appropriate" );
   	File current = file_chooser.getCurrentDirectory();
   	File manifest = new File( current, "imsmanifest.xml" );
		System.out.println( "Manifest: " + manifest.getAbsolutePath() );
		System.out.println( "Manifest: " + manifest.exists() );
   	setEnabled( !manifest.exists() );
   	}
   	
   public void actionPerformed(ActionEvent e)
   	{
   	if ( e.getSource() == this )
   		{
	   	File current = file_chooser.getCurrentDirectory();
   		File manifest = new File( current, "imsmanifest.xml" );
   		if ( !manifest.exists() )
   			{
   			try
   				{
   				manifest.createNewFile();
   				file_chooser.rescanCurrentDirectory();
   				file_chooser.ensureFileIsVisible( manifest );
   				}
   			catch ( IOException ioex )
   				{
   				}

   			}
   		}

   	}

    public void propertyChange(PropertyChangeEvent e)
		{
		System.out.println( "Property change received by Button" );
		String prop = e.getPropertyName();
		if ( prop.equals( JFileChooser.DIRECTORY_CHANGED_PROPERTY ) )
			{
			enableAsAppropriate();
			file_chooser.setSelectedFile( null );
			}
			
		//if ( prop.equals( JFileChooser.SELECTED_FILE_CHANGED_PROPERTY ) )
		//	{
		//	File selected = file_chooser.getSelectedFile();
		//	file_chooser.setControlButtonsAreShown( selected!=null && selected.isFile() );
		//	}
		}    
	}
	
	private class MyFileChooser extends JFileChooser
		{
		public boolean accept( File selected )
			{
			return selected!=null && selected.isFile() && selected.getName().equalsIgnoreCase( "imsmanifest.xml" );
			}

		}

	}
