/**
 *#########################################################################
 *
 * A component of the Gatherer application, part of the Greenstone digital
 * library suite from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * <BR><BR>
 *
 * Author: John Thompson, Greenstone Digital Library, University of Waikato
 *
 * <BR><BR>
 *
 * Copyright (C) 1999 New Zealand Digital Library Project
 *
 * <BR><BR>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * <BR><BR>
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * <BR><BR>
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *########################################################################
 */
package org.greenstone.gatherer.gui;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.*;
import javax.swing.event.*;

import org.greenstone.gatherer.Configuration;
import org.greenstone.gatherer.DebugStream;
import org.greenstone.gatherer.Dictionary;
import org.greenstone.gatherer.Gatherer;
import org.greenstone.gatherer.collection.BasicCollectionConfiguration;
import org.greenstone.gatherer.greenstone.LocalGreenstone;
import org.greenstone.gatherer.shell.GShell;
import org.greenstone.gatherer.shell.GShellEvent;
import org.greenstone.gatherer.shell.GShellListener;
import org.greenstone.gatherer.shell.GDefaultProgressMonitor;
import org.greenstone.gatherer.util.ArrayTools;
import org.greenstone.gatherer.util.CheckList;
import org.greenstone.gatherer.util.CheckListEntry;
import org.greenstone.gatherer.util.StaticStrings;
import org.greenstone.gatherer.util.Utility;

/** This class provides the functionality to export a set of current
 * collections from the GSDLHOME/collect/ directory to various formats
 * (hence ExportAs) using export.pl. The user chooses the collection from a
 * list, where each entry also displays details about itself, confirms the
 * delete of a collection by checking a checkbox then presses the ok button
 * to actually delete the collection.  
 * Copied from WriteCDImagePrompt
 * @author John Thompson, Greenstone Digital Library, University of Waikato
 * @version 2.3
 */
public class ExportAsPrompt
    extends ModalDialog 
    implements GShellListener {

    static final private Dimension LABEL_SIZE = new Dimension(120, 25);
    
    private OKButtonListener ok_button_listener;

    private JLabel saveas_label = null;
    private JComboBox saveas_combobox = null;

    private ArrayList all_collections = null;
    private BasicCollectionConfiguration selected_collection = null;
  /** The list of collections to export */
    private JList list = null;
    /** The currently selected collection for deletion. */
    private BasicCollectionConfiguration collection = null;
    /** A reference to ourself so any inner-classes can dispose of us. */
    private ExportAsPrompt prompt = null;
    /** The close button, which exits the prompt without deleting anything. */
    private JButton cancel_button = null;
    /** The ok button which causes the selected collection to be deleted. */
    private JButton ok_button = null;
    /** The label above details. */
    private JLabel details_label = null;
    /** The label above the list. */
    private JLabel list_label = null;
    /** The text area used to display details about the collection selected. */
    private JTextArea details_textarea = null;
    /** The text area used to display instructions for the cd-rom/dvd export */
    private JTextArea instructions_textarea;
    /** A string array used to pass arguments to the phrase retrieval method. */
    private JTextField title_field = null;
    private JLabel title_label = null;
    private String args[] = null;
    private String cd_title = null;
    /** whether the exporting was successful or not */
    private boolean successful = false;
    /** whether we are trying to export or not */
    private boolean exporting = false;
    /** the error message if any */
    private StringBuffer error_message = null;
    /** The size of the export prompt screen. */
    public static final Dimension SIZE = new Dimension(500, 540);  
    private GDefaultProgressMonitor progress_monitor;    

    private JButton convert_xml_button1 = null;
    private JButton convert_xml_button2 = null;
    private JButton convert_xml_button3 = null;
    private JButton folder_button = null;

    private JPanel instructions_pane = null;
    
    private JPanel convert_xml_pane1 = null;
    private JPanel convert_xml_pane2 = null;
    private JPanel mapping_xml_pane = null;

    private JCheckBox convert_xml_checkbox1 = null; 
    private JCheckBox convert_xml_checkbox2 = null;
    private JCheckBox mapping_xml_checkbox = null;
    
    private JCheckBox output_single_checkbox = null;  

    private JTextField convert_xml_field1 = null;
    private JTextField convert_xml_field2 = null;
    private JTextField mapping_xml_field = null;


    private File xsl_file1 = null;
    private File xsl_file2 = null;
    private File mapping_file = null;

    private JPanel convert_xml_pane = null; 

    private HashMap plugoutMap = new HashMap();
  

    /** Constructor.
     * @see org.greenstone.gatherer.collection.ExportAsPrompt.CancelButtonListener
     * @see org.greenstone.gatherer.collection.ExportAsPrompt.CollectionListListener
     * @see org.greenstone.gatherer.collection.ExportAsPrompt.OKButtonListener
     */
    public ExportAsPrompt() {
	super(Gatherer.g_man, true);
	this.setComponentOrientation(Dictionary.getOrientation());
	plugoutMap.clear();         
	plugoutMap.put("DSpace","dublin-core.xml");
        plugoutMap.put("MARCXML","doc.xml");   
	plugoutMap.put("GreenstoneMETS","doctxt.xml,docmets.xml");     
	plugoutMap.put("FedoraMETS","doctxt.xml,docmets.xml");     

	// this is the order we want them to appear in the list
	String [] saveas_formats = {"GreenstoneMETS", "FedoraMETS", "MARCXML", "DSpace"};
        cancel_button = new GLIButton(Dictionary.get("General.Close"), Dictionary.get("General.Close_Tooltip"));
	
	details_textarea = new JTextArea(Dictionary.get("DeleteCollectionPrompt.No_Collection"));
	details_textarea.setEditable(false);
	details_textarea.setComponentOrientation(Dictionary.getOrientation());
        
	details_label = new JLabel(Dictionary.get("DeleteCollectionPrompt.Collection_Details"));
	details_label.setComponentOrientation(Dictionary.getOrientation());

	instructions_textarea = new JTextArea(Dictionary.get("ExportAsPrompt.Instructions"));
	instructions_textarea.setCaretPosition(0);
	instructions_textarea.setEditable(false);
	instructions_textarea.setLineWrap(true);
	instructions_textarea.setRows(4);
	instructions_textarea.setWrapStyleWord(true);
	instructions_textarea.setComponentOrientation(Dictionary.getOrientation());
             
       
        saveas_label = new JLabel(Dictionary.get("ExportAsPrompt.SaveAs"));
        saveas_label.setComponentOrientation(Dictionary.getOrientation());
        //saveas_label.setPreferredSize(LABEL_SIZE);
        
	saveas_combobox = new JComboBox(saveas_formats);
	saveas_combobox.setOpaque(false);
	saveas_combobox.setToolTipText(Dictionary.get("ExportAsPrompt.SaveAs_Tooltip"));
        saveas_combobox.setComponentOrientation(Dictionary.getOrientation());

	// Add xml conversion feature
	convert_xml_button1 = new GLIButton(Dictionary.get("ExportAsPrompt.Browse"),Dictionary.get("ExportAsPrompt.Browse_Tooltip"));
	convert_xml_button1.setEnabled(false);

	convert_xml_button2 = new GLIButton(Dictionary.get("ExportAsPrompt.Browse"),Dictionary.get("ExportAsPrompt.Browse_Tooltip"));
	convert_xml_button2.setEnabled(false);
	
	convert_xml_button3 = new GLIButton(Dictionary.get("ExportAsPrompt.Browse"),Dictionary.get("ExportAsPrompt.Browse_Tooltip"));
	convert_xml_button3.setEnabled(false);

	convert_xml_checkbox1 = new JCheckBox();
        convert_xml_checkbox1.setText(Dictionary.get("ExportAsPrompt.ApplyXSL","doc.xml"));
        convert_xml_checkbox1.setToolTipText(Dictionary.get("ExportAsPrompt.ApplyXSL_Tooltip"));
        convert_xml_checkbox1.setComponentOrientation(Dictionary.getOrientation());
        
	convert_xml_checkbox2 = new JCheckBox();
        convert_xml_checkbox2.setToolTipText(Dictionary.get("ExportAsPrompt.ApplyXSL_Tooltip"));
        convert_xml_checkbox2.setComponentOrientation(Dictionary.getOrientation());
        
        output_single_checkbox = new JCheckBox();
        output_single_checkbox.setComponentOrientation(Dictionary.getOrientation());
	output_single_checkbox.setText(Dictionary.get("ExportAsPrompt.MARCXMLGroup"));
        output_single_checkbox.setToolTipText(Dictionary.get("ExportAsPrompt.MARCXMLGroup_Tooltip"));


        mapping_xml_checkbox = new JCheckBox();
        mapping_xml_checkbox.setComponentOrientation(Dictionary.getOrientation());
	mapping_xml_checkbox.setText(Dictionary.get("ExportAsPrompt.MappingXML"));
        mapping_xml_checkbox.setToolTipText(Dictionary.get("ExportAsPrompt.MappingXML_Tooltip"));

        convert_xml_field1 = new JTextField();
        convert_xml_field1.setComponentOrientation(Dictionary.getOrientation());
	convert_xml_field1.setEnabled(false);

	convert_xml_field2 = new JTextField();
        convert_xml_field2.setComponentOrientation(Dictionary.getOrientation());
	convert_xml_field2.setEnabled(false);

	mapping_xml_field = new JTextField();
        mapping_xml_field.setComponentOrientation(Dictionary.getOrientation());
	mapping_xml_field.setEnabled(false);

        convert_xml_pane1 = new JPanel(new BorderLayout());
	convert_xml_pane1.setComponentOrientation(Dictionary.getOrientation());                
        
	convert_xml_pane2 = new JPanel(new BorderLayout());
        convert_xml_pane2.setComponentOrientation(Dictionary.getOrientation());
        
	mapping_xml_pane = new JPanel(new BorderLayout());
        mapping_xml_pane.setComponentOrientation(Dictionary.getOrientation());
        
	convert_xml_pane = new JPanel(new GridLayout(3,1));
        convert_xml_pane.setComponentOrientation(Dictionary.getOrientation());
        
	all_collections = new ArrayList();
	//list = new CheckList(true);
	list = new JList(getCollectionListModel());
	list.setComponentOrientation(Dictionary.getOrientation());
	list_label = new JLabel(Dictionary.get("DeleteCollectionPrompt.Collection_List"));
	list_label.setComponentOrientation(Dictionary.getOrientation());
        
	ok_button = new GLIButton(Dictionary.get("ExportAsPrompt.Export"), Dictionary.get("ExportAsPrompt.Export_Tooltip"));
	
	title_field = new JTextField();
        title_field.setComponentOrientation(Dictionary.getOrientation());
	title_field.setToolTipText(Dictionary.get("ExportAsPrompt.Export_Name_Tooltip"));
	title_label = new JLabel(Dictionary.get("ExportAsPrompt.Export_Name"));
        title_label.setComponentOrientation(Dictionary.getOrientation());
        
        folder_button = new GLIButton(Dictionary.get("ExportAsPrompt.Browse"),Dictionary.get("ExportAsPrompt.Browse_Tooltip"));
	folder_button.addActionListener(new FolderButtonListener());
   
       
	prompt = this;
	setSize(SIZE);
	setTitle(Dictionary.get("ExportAsPrompt.Title"));

	setJMenuBar(new SimpleMenuBar("exporting")); 
	cancel_button.addActionListener(new CancelButtonListener());
	list.addListSelectionListener(new CollectionListListener());
	list.clearSelection();
	list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	ok_button_listener = new OKButtonListener();
	ok_button.addActionListener(ok_button_listener);
	ok_button.setEnabled(false);
	//title.getDocument().addDocumentListener(new DocumentListener());

       	convert_xml_button1.addActionListener(new ConvertXMLButtonListener());
	convert_xml_checkbox1.addActionListener(new ConvertXMLCheckboxListener());
	mapping_xml_checkbox.addActionListener(new ConvertXMLCheckboxListener());
	convert_xml_button3.addActionListener(new ConvertXMLButtonListener());
   
	convert_xml_button2.addActionListener(new ConvertXMLButtonListener());
	convert_xml_checkbox2.addActionListener(new ConvertXMLCheckboxListener());

        saveas_combobox.addActionListener(new SaveasListener());        

    }

    /** Destructor. */
    public void destroy() {
        saveas_label = null;
	saveas_combobox = null;
	all_collections.clear();
	all_collections = null;
	cancel_button = null;
	details_textarea = null;
	details_label = null;
	list = null;
	ok_button = null;
	prompt = null;
	selected_collection = null;
	title_field = null;
	title_label = null;
    }

    /** This method causes the modal prompt to be displayed. 
     * returns true if it has exported the collections that are currently selected */
    public boolean display() {
        JScrollPane scrol_tmp;
	// Top pane
	instructions_pane = new JPanel(new BorderLayout());
        instructions_pane.setComponentOrientation(Dictionary.getOrientation());
        instructions_pane.setBorder(BorderFactory.createEmptyBorder(0,0,5,5));
        scrol_tmp = new JScrollPane(instructions_textarea);
        scrol_tmp.setComponentOrientation(Dictionary.getOrientation());
        instructions_pane.add(scrol_tmp, BorderLayout.CENTER);
	
	title_label.setBorder(BorderFactory.createEmptyBorder(0,5,0,15));

	JPanel title_pane = new JPanel(new BorderLayout());
        title_pane.setComponentOrientation(Dictionary.getOrientation());
	title_pane.add(title_label, BorderLayout.LINE_START);
	title_pane.add(title_field, BorderLayout.CENTER);
        title_pane.add(folder_button, BorderLayout.LINE_END);
        //apply xsl pane
          
	convert_xml_pane1.removeAll();
        convert_xml_pane2.removeAll();
	mapping_xml_pane.removeAll();
	convert_xml_pane.removeAll();

	convert_xml_pane1.add(convert_xml_checkbox1, BorderLayout.LINE_START);
	convert_xml_pane1.add(convert_xml_field1, BorderLayout.CENTER);
	convert_xml_pane1.add(convert_xml_button1, BorderLayout.LINE_END);

	convert_xml_pane2.add(convert_xml_checkbox2, BorderLayout.LINE_START);
	convert_xml_pane2.add(convert_xml_field2, BorderLayout.CENTER);
	convert_xml_pane2.add(convert_xml_button2, BorderLayout.LINE_END);
      
	mapping_xml_pane.add(mapping_xml_checkbox, BorderLayout.LINE_START);
	mapping_xml_pane.add(mapping_xml_field, BorderLayout.CENTER);
	mapping_xml_pane.add(convert_xml_button3, BorderLayout.LINE_END);

	convert_xml_pane.add(convert_xml_pane1);
       	
        String saveas = (String)saveas_combobox.getSelectedItem();
	// force the updating of which fields we are displaying
	saveas_combobox.setSelectedIndex(0);

        // Save as pane
	JPanel saveas_pane = new JPanel(new BorderLayout());
        saveas_pane.setComponentOrientation(Dictionary.getOrientation());
	saveas_label.setBorder(BorderFactory.createEmptyBorder(0,5,0,15));
	saveas_pane.add(saveas_label, BorderLayout.LINE_START);
	saveas_pane.add(saveas_combobox, BorderLayout.CENTER);

        JPanel tmp_pane = new JPanel(new BorderLayout());
        tmp_pane.setComponentOrientation(Dictionary.getOrientation());
        tmp_pane.add(saveas_pane, BorderLayout.NORTH);
	tmp_pane.add(title_pane, BorderLayout.CENTER);

	instructions_pane.add(tmp_pane, BorderLayout.NORTH);          

	instructions_pane.add(convert_xml_pane, BorderLayout.CENTER);

	// Central pane
	JPanel list_pane = new JPanel(new BorderLayout());
        list_pane.setComponentOrientation(Dictionary.getOrientation());
	list_pane.add(list_label, BorderLayout.NORTH);
        scrol_tmp = new JScrollPane(list);
        scrol_tmp.setComponentOrientation(Dictionary.getOrientation());
	list_pane.add(scrol_tmp, BorderLayout.CENTER);
	list_pane.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));

	JPanel details_pane = new JPanel(new BorderLayout());
        details_pane.setComponentOrientation(Dictionary.getOrientation());
	details_pane.add(details_label, BorderLayout.NORTH);
        scrol_tmp = new JScrollPane(details_textarea);
        scrol_tmp.setComponentOrientation(Dictionary.getOrientation());
	details_pane.add(scrol_tmp, BorderLayout.CENTER);
	details_pane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

	JPanel central_pane = new JPanel(new GridLayout(2, 1));
        central_pane.setComponentOrientation(Dictionary.getOrientation());
	central_pane.add(list_pane);
	central_pane.add(details_pane);
	central_pane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

	// Lower pane
	JPanel button_pane = new JPanel(new GridLayout(1, 2));
        button_pane.setComponentOrientation(Dictionary.getOrientation());
	button_pane.add(ok_button);
	button_pane.add(cancel_button);
	button_pane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

	JPanel lower_pane = new JPanel(new BorderLayout());
        lower_pane.setComponentOrientation(Dictionary.getOrientation());
	lower_pane.add(button_pane, BorderLayout.SOUTH);
	lower_pane.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));

	// Final.
	JPanel content_pane = (JPanel)this.getContentPane();
        content_pane.setComponentOrientation(Dictionary.getOrientation());
	content_pane.setLayout(new BorderLayout());
	content_pane.add(instructions_pane, BorderLayout.NORTH);
	content_pane.add(central_pane, BorderLayout.CENTER);
	content_pane.add(lower_pane, BorderLayout.SOUTH);

	// Center and display.
	Dimension screen_size = Configuration.screen_size;
	this.setLocation((screen_size.width - SIZE.width) / 2, (screen_size.height - SIZE.height) / 2);
	this.setVisible(true); // blocks until the dialog is killed
	return true;
	
    }

    
    /** This method calls the builcol.pl scripts via a GShell so as to not lock up the processor.
     * @see org.greenstone.gatherer.Configuration
     * @see org.greenstone.gatherer.Gatherer
     * @see org.greenstone.gatherer.collection.Collection
     * @see org.greenstone.gatherer.gui.BuildOptions
     * @see org.greenstone.gatherer.shell.GShell
     * @see org.greenstone.gatherer.shell.GShellListener
     * @see org.greenstone.gatherer.shell.GShellProgressMonitor
     * @see org.greenstone.gatherer.util.Utility
     */
    public void exportAsCollections() {
	DebugStream.println("ExportAsPrompt.exportAsCollections()");

	if (selected_collection == null) return;

	cd_title = title_field.getText();

	String export_type = (String) saveas_combobox.getSelectedItem();
      
	// Generate the export.pl command
	ArrayList command_parts_list = new ArrayList();
	if (!Gatherer.isGsdlRemote) {
	    command_parts_list.add(Configuration.perl_path);
	    command_parts_list.add("-S");
	}
	command_parts_list.add(LocalGreenstone.getBinScriptDirectoryPath() + "export.pl");
	command_parts_list.add("-gli");
	command_parts_list.add("-language");
	command_parts_list.add(Configuration.getLanguage());
	command_parts_list.add("-removeold");
	command_parts_list.add("-saveas");
	command_parts_list.add(export_type);
	// we want to be able to export items from other collect directories too
	String collectDir = Gatherer.getCollectDirectoryPath();

	if(Gatherer.GS3) {
	    command_parts_list.add("-site");
	    command_parts_list.add(Configuration.site_name);
	}

	if(collectDir != Gatherer.getDefaultGSCollectDirectoryPath(true)) {
		command_parts_list.add("-collectdir");
		command_parts_list.add(collectDir);
	}	
	command_parts_list.add("-exportdir");
	String export_dir = LocalGreenstone.getTmpDirectoryPath();
       	if (cd_title.equals("")) {
            export_dir += "exported_" + selected_collection.getShortName()+ "_" +export_type;
	}
	else {
	    File cd_file = new File(cd_title);
            if (cd_file.isAbsolute())
		export_dir = cd_title + File.separator + "exported_"  + selected_collection.getShortName()+ "_"+ export_type;
	    else{
                cd_title = cd_title.replaceAll("\\s+","");
                cd_title = cd_title.replaceAll("\\\\+","/");
                cd_title = cd_title.replaceAll("/+","/");
            	export_dir +=cd_title;
	    }
	}

        command_parts_list.add(export_dir);

	// check the xslt/mapping file values.
	
	// now we build up the saveas options
	StringBuffer saveas_options = new StringBuffer();
	
	if (export_type.equals("MARCXML")){
	  if (!convert_xml_field1.getText().equals("")) {
	    saveas_options.append("-xslt_file ");
	    saveas_options.append(convert_xml_field1.getText()+" "); 
	  }
	  if (!mapping_xml_field.getText().equals("")) {
	      saveas_options.append("-mapping_file ");
	      saveas_options.append(mapping_xml_field.getText()+" ");
	  }
	    if (output_single_checkbox.isSelected()){
	      saveas_options.append("-group ");
	    }
	}
	else if (export_type.endsWith("METS")) {
	  if (!convert_xml_field1.getText().equals("")) {
	    saveas_options.append("-xslt_txt ");
	    saveas_options.append(convert_xml_field1.getText()+" "); 
	  }
	  if (!convert_xml_field2.getText().equals("")) {
	    saveas_options.append("-xslt_mets ");
	    saveas_options.append(convert_xml_field2.getText()+" "); 
	  }
	}
	else if (export_type.equals("DSpace")) {
	  if (!convert_xml_field1.getText().equals("")) {
	    saveas_options.append("-xslt_file ");
	    saveas_options.append(convert_xml_field1.getText()+" "); 
	  }
	}
       
	 if (saveas_options.length()>0) {
	     command_parts_list.add("-saveas_options");
	     command_parts_list.add(saveas_options.toString());
	 }
	 
	 command_parts_list.add( selected_collection.getShortName());
	 

	DebugStream.print("export command = ");
	for (int i = 0; i < command_parts_list.size(); i++) {
	    DebugStream.print(command_parts_list.get(i) + " ");
	    //System.err.print("'"+command_parts_list.get(i)+"'" + " ");          
	}
	DebugStream.println("");

	// Run the export.pl command
	String[] command_parts = (String[]) command_parts_list.toArray(new String[0]);

        progress_monitor = new  GDefaultProgressMonitor();

	GShell process = new GShell(command_parts, GShell.EXPORTAS, 3, this,progress_monitor , GShell.GSHELL_EXPORTAS);
	process.start();
	//process.run();
	DebugStream.println("ExportAsPrompt.exportAsCollections().return");
	
    }


    public void cancelExporting(){
	progress_monitor.setStop(true);           
    }


    /** Shows an export complete prompt. 
     * @param success A <strong>boolean</strong> indicating if the collection was successfully deleted.
     * @see org.greenstone.gatherer.collection.Collection
     */
    public void resultPrompt(boolean success, String extra) {
	args = new String[2];
	
	// coll name
	args[0] = selected_collection.getName() + StaticStrings.SPACE_CHARACTER + StaticStrings.LBRACKET_CHARACTER + selected_collection.getShortName() + StaticStrings.RBRACKET_CHARACTER;
	
	String export_type = (String) saveas_combobox.getSelectedItem();       
       	args[1] = LocalGreenstone.getTmpDirectoryPath();
       	if (cd_title.equals("")) {
           args[1] += "exported_" + selected_collection.getShortName()+"_"+export_type;
	}
	else {
	    File cd_file = new File(cd_title);
            if (cd_file.isAbsolute())
		args[1] = cd_title + File.separator + "exported_" + selected_collection.getShortName()+"_"+export_type;
	    else{
                cd_title = cd_title.replaceAll("\\s+","");
                cd_title = cd_title.replaceAll("\\\\+","/");
                cd_title = cd_title.replaceAll("/+","/");
            	args[1] +=cd_title;
	    }
	}
        

	String title;
	String label;
	String details;

	if (success) {
	  String successMessage = "ExportAsPrompt.Successful_ExportOne";
	  title = Dictionary.get("ExportAsPrompt.Successful_Title");
	  label = Dictionary.get(successMessage, args);
	  details = Dictionary.get("ExportAsPrompt.Successful_Details", args);
	} else {
	  String failedMessage = "ExportAsPrompt.Failed_ExportOne";
	  title = Dictionary.get("ExportAsPrompt.Failed_Title");
	  label = Dictionary.get(failedMessage, args);
	  details = Dictionary.get("ExportAsPrompt.Failed_Details", args);
	}
	SimpleResultDialog result_dialog = new SimpleResultDialog(this, title, label, details);
	result_dialog.setVisible(true); // Blocks
	result_dialog.dispose();
	result_dialog = null;
    }

    /** Method to scan the collect directory retrieving and reloading each collection it finds, while building the list of known collections.
     * @see org.greenstone.gatherer.Configuration
     * @see org.greenstone.gatherer.Gatherer
     * @see org.greenstone.gatherer.util.ArrayTools
     * @see org.greenstone.gatherer.util.Utility
     */
  private ListModel getCollectionListModel() {
    DefaultListModel model = new DefaultListModel();
	// Start at the collect dir.
	File collect_directory = new File(Gatherer.getCollectDirectoryPath());
	String file_name = (Gatherer.GS3)? Utility.CONFIG_GS3_FILE : Utility.CONFIG_FILE;
	if (collect_directory.exists()) {
	    // Now for each child directory see if it contains a .col file and
	    // if so try to load it..
	    File collections[] = collect_directory.listFiles();
	    ArrayTools.sort(collections);
	    for(int i = 0; collections != null && i < collections.length; i++) {
		if(collections[i].isDirectory() && !collections[i].getName().equals(StaticStrings.MODEL_COLLECTION_NAME)) {
		    File config_file = new File(collections[i], file_name);
		    if (config_file.exists()) {
			BasicCollectionConfiguration config = new BasicCollectionConfiguration(config_file);
			model.addElement(config);		        
			config = null;
		    }
		}
	    }
	}
	return model;
	// Otherwise the collect directory doesn't actually exist, so there ain't much we can do.
  }


    /** All implementation of GShellListener must include this method so the listener can be informed of messages from the GShell.
     * @param event A <strong>GShellEvent</strong> that contains, amoung other things, the message.
     */
    public synchronized void message(GShellEvent event) {
	// Ignore the messages from RecPlug with 'show_progress' set (used for progress bars)
	String message = event.getMessage();
	int len = "export.pl> ".length();
	if (message.startsWith("export.pl>")) {
	    message = message.substring(len);
	    //DebugStream.println("message = "+event.getMessage());
	    error_message.append(message);
	    error_message.append("\n");
	}
    }

    /** All implementation of GShellListener must include this method so the listener can be informed when a GShell begins its task. Implementation side-effect, not actually used.
     * @param event A <strong>GShellEvent</strong> that contains details of the initial state of the <strong>GShell</strong> before task comencement.
     */
    public synchronized void processBegun(GShellEvent event) {
	// We don't care. 
    }
    /** All implementation of GShellListener must include this method so the listener can be informed when a GShell completes its task.
     * @param event A <strong>GShellEvent</strong> that contains details of the final state of the <strong>GShell</strong> after task completion.
     */
    public synchronized void processComplete(GShellEvent event) {
	successful = false;
	if(event.getStatus() == GShell.OK) {
	    if(event.getType() == GShell.EXPORTAS) {
		successful = true;
	    }
	}
	ok_button_listener.processComplete();
    }

    /** A button listener implementation, which listens for actions on the close button and disposes of the dialog when detected. */
    private class CancelButtonListener 
	implements ActionListener {
	/** Any implementation of ActionListener must include this method so we can be informed when the button is actioned.
	 * @param event An <strong>ActionEvent</strong> containing all the relevant information garnered from the event itself.
	 */
	public void actionPerformed(ActionEvent event) {
	    prompt.dispose();
	}
    }

    /** This private class listens for selection events in from the list and then displays the appropriate details for that collection.
     */
    private class CollectionListListener 
	implements ListSelectionListener
    {
	/** Any implementation of ListSelectionListener must include this method so we can be informed when the list selection changes.
	 * @param  event a <strong>ListSelectionEvent</strong> containing all the relevant information garnered from the event itself
	 */
	public void valueChanged(ListSelectionEvent event)
	{
	    // Can only export when something is ticked
	    //ok_button.setEnabled(!list.isNothingTicked());

	    if (list.isSelectionEmpty()) {
		details_textarea.setText(Dictionary.get("DeleteCollectionPrompt.No_Collection"));
		ok_button.setEnabled(false);
	    }
	    else {
	      BasicCollectionConfiguration collection = (BasicCollectionConfiguration) list.getSelectedValue();
	      args = new String[3];
	      args[0] = collection.getCreator();
	      args[1] = collection.getMaintainer();
	      args[2] = collection.getDescription();
	      details_textarea.setText(Dictionary.get("DeleteCollectionPrompt.Details", args));
	      details_textarea.setCaretPosition(0);
	      ok_button.setEnabled(true);
	    }
	}

    }
    /** The OK button listener implementation. */
    private class OKButtonListener 
	implements ActionListener {
	private Component glass_pane;
	private MouseListener mouse_blocker_listener;
	private ProgressDialog progress_dialog;

	/** Any implementation of ActionListener must include this method so we can be informed when the button is actioned.
	 * @param event An <strong>ActionEvent</strong> containing all the relevant information garnered from the event itself.
	 * @see org.greenstone.gatherer.Configuration
	 * @see org.greenstone.gatherer.Gatherer
	 * @see org.greenstone.gatherer.util.Utility
	 */
	public void actionPerformed(ActionEvent event) {
	    ///ystem.err.println("OK Clicked");
	    // Make sure there are some colls specified
	    selected_collection = (BasicCollectionConfiguration)list.getSelectedValue();
	    error_message = new StringBuffer();
	    
	    // Set the cursor to hourglass
	    glass_pane = getGlassPane();
	    mouse_blocker_listener = new MouseAdapter() {};
	    glass_pane.addMouseListener(mouse_blocker_listener);
	    glass_pane.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
	    glass_pane.setVisible(true);

	    // Export the selected collection.
	    ///ystem.err.println("Exporting As for named collections");
	    exportAsCollections();

	    // Show progress dialog
	    ///ystem.err.println("Showing progress dialog");
	    progress_dialog = new ProgressDialog();
	    progress_dialog.setVisible(true);
	}

	public void processComplete() {
	  Gatherer.invokeInEDT_replacesProceedInCurrThread("ExportAsPrompt.processComplete()", Gatherer.ASYNC, new Runnable() {
           public void run() {
	    ///ystem.err.println("Process complete");
	    // Dispose of progress dialog
	  
	    progress_dialog.setVisible(false);
	    progress_dialog.dispose();
	    progress_dialog = null;

	    // unset the cursor
	    glass_pane.setVisible(false);
	    glass_pane.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
	    glass_pane.removeMouseListener(mouse_blocker_listener);
	    glass_pane = null;
	    mouse_blocker_listener= null;
	    
	    if (successful) {
		resultPrompt(true, error_message.toString());
	    } else {
		resultPrompt(false, error_message.toString());
	    }
	    error_message = null;
             
            convert_xml_button1.setEnabled(false); 
            xsl_file1 = null;
            convert_xml_field1.setText("");
            convert_xml_checkbox1.setSelected(false);

	    convert_xml_button2.setEnabled(false); 
            xsl_file2 = null;
            convert_xml_field2.setText("");
            convert_xml_checkbox2.setSelected(false);

	    mapping_xml_checkbox.setSelected(false);
	    output_single_checkbox.setSelected(false);
	    convert_xml_button3.setEnabled(false);
            mapping_xml_field.setText("");
	    mapping_file = null;
	   }
          });
	}

	private class ProgressDialog 
	    extends ModalDialog {
	    
	    private Dimension size = new Dimension(400,110);
	    
	    public ProgressDialog() {
		super(Gatherer.g_man, Dictionary.get("ExportAsPrompt.Title"), true);
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		setSize(size);
		JPanel content_pane = (JPanel) getContentPane();
		JLabel progress_label = new JLabel(Dictionary.get("ExportAsPrompt.Progress_Label"));
		
		JProgressBar progress_bar = new JProgressBar();
		progress_bar.setIndeterminate(true);
		content_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
		GLIButton cancel_button = new GLIButton(Dictionary.get("ExportAsPrompt.Cancel"),Dictionary.get("ExportAsPrompt.Cancel_Tooltip"));
		cancel_button.setMnemonic(KeyEvent.VK_C);
	
		cancel_button.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
			    cancelExporting();
			}

                });

                JPanel cancel_panel = new JPanel(new FlowLayout(FlowLayout.CENTER,0,0));
		cancel_panel.add(cancel_button);
                                    
		content_pane.setLayout(new BorderLayout(0,5));
		content_pane.add(progress_label, BorderLayout.NORTH);
		content_pane.add(progress_bar, BorderLayout.CENTER);
		content_pane.add(cancel_panel, BorderLayout.SOUTH);

		// Position
		Rectangle frame_bounds = Gatherer.g_man.getBounds();
		setLocation(frame_bounds.x + (frame_bounds.width - size.width) / 2, frame_bounds.y + (frame_bounds.height - size.height) / 2);
	    }
	}
    }

   private class ConvertXMLCheckboxListener implements ActionListener {
	public void actionPerformed(ActionEvent event) {
	  
	    convert_xml_button1.setEnabled(convert_xml_checkbox1.isSelected());
	    convert_xml_field1.setEnabled(convert_xml_checkbox1.isSelected());
	    convert_xml_button2.setEnabled(convert_xml_checkbox2.isSelected());
	    convert_xml_field2.setEnabled(convert_xml_checkbox2.isSelected());
	    convert_xml_button3.setEnabled(mapping_xml_checkbox.isSelected());
	    mapping_xml_field.setEnabled(mapping_xml_checkbox.isSelected());
			
	}
    }


     
    private class SaveasListener implements ActionListener {
    
	public void actionPerformed(ActionEvent event) {
		
	    convert_xml_checkbox1.setSelected(false);
	    convert_xml_checkbox2.setSelected(false);
	    mapping_xml_checkbox.setSelected(false);
	    output_single_checkbox.setSelected(false);

	    convert_xml_button1.setEnabled(false);
            convert_xml_button2.setEnabled(false);
	    convert_xml_button3.setEnabled(false);

            convert_xml_field1.setText("");
	    convert_xml_field2.setText("");
	    mapping_xml_field.setText("");
	    
	    String saveas = (String)saveas_combobox.getSelectedItem();

	    if (convert_xml_pane.getComponentCount() > 1){
		convert_xml_pane.remove(1);
		if (convert_xml_pane.getComponentCount() > 1){
		    convert_xml_pane.remove(1);
		}
	    }

	    if (!saveas.endsWith("METS")){
	
		convert_xml_checkbox1.setText(Dictionary.get("ExportAsPrompt.ApplyXSL",(String)plugoutMap.get(saveas)));	
		if (saveas.equals("MARCXML")){
		    convert_xml_pane.add(mapping_xml_pane);
		    convert_xml_pane.add(output_single_checkbox);
		}		
	    }
	    else{
		String[] docs = ((String)plugoutMap.get(saveas)).split(",");
		convert_xml_checkbox1.setText(Dictionary.get("ExportAsPrompt.ApplyXSL",docs[0]));
		convert_xml_checkbox2.setText(Dictionary.get("ExportAsPrompt.ApplyXSL",docs[1])); 
		convert_xml_pane.add(convert_xml_pane2); 		
	    }
	    
	    convert_xml_pane.revalidate();
	    convert_xml_pane.repaint();
            instructions_pane.revalidate();
            instructions_pane.repaint();
             
	}
	
    }
       
     private class ConvertXMLButtonListener implements ActionListener {
	public void actionPerformed(ActionEvent event) {
	    JFileChooser chooser = new JFileChooser();
	    // Note: source for ExampleFileFilter can be found in FileChooserDemo,
	    // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
	    javax.swing.filechooser.FileFilter filter = new javax.swing.filechooser.FileFilter(){
		    public boolean accept(File f){
			return f.getPath().endsWith(".xsl")||f.isDirectory()||f.getPath().endsWith(".xml");
		    }  

		    public String getDescription(){
			return "XSL or XML file";
		    }          
      };
	    
	    chooser.setFileFilter(filter);
	    int returnVal = chooser.showOpenDialog(prompt);        

	    if(returnVal == JFileChooser.APPROVE_OPTION) {
		if (event.getSource() == convert_xml_button1){

		    xsl_file1 = chooser.getSelectedFile();
		    convert_xml_field1.setText(xsl_file1.getPath());
		}
                else if (event.getSource() == convert_xml_button2){ 
                     xsl_file2 = chooser.getSelectedFile();
		    convert_xml_field2.setText(xsl_file2.getPath());
		   
		}
		else {
		    mapping_file = chooser.getSelectedFile();
		    mapping_xml_field.setText(mapping_file.getPath()); 
		}
	    }
	}
     }

 private class FolderButtonListener implements ActionListener {
	public void actionPerformed(ActionEvent event) {
	    JFileChooser chooser = new JFileChooser();
	    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
	   
	    int returnVal = chooser.showOpenDialog(prompt);        
	    
	    if(returnVal == JFileChooser.APPROVE_OPTION) {
		File folder_name = chooser.getSelectedFile();
		title_field.setText(folder_name.getPath());
	    }
	    
	}
 }
}





