/**
 *#########################################################################
 *
 * 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.
 *
 * Author: John Thompson, Greenstone Digital Library, University of Waikato
 *
 * Copyright (C) 1999 New Zealand Digital Library Project
 *
 * 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.
 *
 * 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.
 *
 * 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.cdm;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.*;
import javax.swing.plaf.basic.*;
import org.apache.xerces.parsers.*;
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.CollectionContentsChangedListener;
import org.greenstone.gatherer.collection.CollectionManager;
import org.greenstone.gatherer.greenstone.Plugins;
import org.greenstone.gatherer.gui.DesignPaneHeader;
import org.greenstone.gatherer.gui.GComboBox;
import org.greenstone.gatherer.gui.GLIButton;
import org.greenstone.gatherer.gui.ModalDialog;
import org.greenstone.gatherer.gui.TestingPreparation;
import org.greenstone.gatherer.gui.WarningDialog;
import org.greenstone.gatherer.util.JarTools;
import org.greenstone.gatherer.util.StaticStrings;
import org.greenstone.gatherer.util.Utility;
import org.greenstone.gatherer.util.XMLTools;
import org.w3c.dom.*;
import org.xml.sax.*;


/** This class is for maintaining a list of known plug-ins, and importing new plugins using the parser. */
public class PluginManager
    extends DOMProxyListModel
    implements CollectionContentsChangedListener
{
    /** When asking how many rows are in the model, and if this variables value is true, then this modifier alters the number returned. This funtionality is used to hide the last three rows of the list in low detail modes. */
    private boolean modify_row_count = false;
    /** The controls for editing the contents of this manager. */
    private Control controls = null;
    private DOMProxyListModel model;
    private JPanel separator;
    private Plugin separator_plugin;

  /** The number of plugins that are fixed 'below the line' */
  private static int NUM_FIXED_PLUGINS = 3; 
    /** Constructor.
     */
    public PluginManager() {	super(CollectionDesignManager.collect_config.getDocumentElement(), StaticStrings.PLUGIN_ELEMENT, new Plugin());
	DebugStream.println("PluginManager: " + super.getSize() + " plugins parsed.");
	model = this;

	// Force the assigned plugins to be loaded and cached now
	for (int i = 0; i < getSize(); i++) {
	    getElementAt(i);
	}
	
	// Create the separator, 'cause we can reuse it.
	Gatherer.invokeInEDT_replacesProceedInCurrThread(
	 "CollectionDesignManager.loadDesignDetails",
	 Gatherer.SYNC,
	 //Gatherer.BYPASS_WHEN_NOT_TESTING,
	 new Runnable() {
	     public void run() {
		 separator = getSeparator();
		 placeSeparator();
	     }
	 });
	// check for MetadataXMLPlug
	ensureMetadataXMLPlugIsLoaded();
	// Listen for CollectionContentsChanged events, so we can give plugin hints when new files are added
	CollectionManager.addCollectionContentsChangedListener(this);
	
    }

    private void ensureMetadataXMLPlugIsLoaded() {

	Plugin metaxmlplug = Plugins.getPlugin(StaticStrings.METADATAXMLPLUG_STR, false);
	if (metaxmlplug!= null) {
	    if (!contains(metaxmlplug)) {
		// Create a new element in the DOM
		Element new_plugin_element = CollectionConfiguration.createElement(StaticStrings.PLUGIN_ELEMENT);
		new_plugin_element.setAttribute(StaticStrings.TYPE_ATTRIBUTE, metaxmlplug.getName());
		Plugin new_plugin = new Plugin(new_plugin_element, metaxmlplug);
		assignPlugin(new_plugin);
	    }
	}
    }


    /** Retrieve a list of the plugins that are available to be added to the collection. */
    private Object[] getAvailablePlugins()
    {
	ArrayList available = new ArrayList();

	// Add all the non-abstract core Greenstone plugins, except for ArcPlug and RecPlug
	ArrayList plugins_list = Plugins.getPluginsList();
	for (int i = 0; i < plugins_list.size(); i++) {
	    Plugin plugin = (Plugin) plugins_list.get(i);
	    if (!plugin.isAbstract()) {
		String plugin_name = plugin.getName();
		if (!plugin_name.equals(StaticStrings.ARCPLUG_STR) && !plugin_name.equals(StaticStrings.RECPLUG_STR) && !plugin_name.equals(StaticStrings.METADATAXMLPLUG_STR)) {
		  available.add(plugin);
		}
	    }
	}
        
	// Sort the available plugins into alphabetical order
	Collections.sort(available);

	return available.toArray();
    }


    public ArrayList getExploderPlugins(File file)
    {
	ArrayList exploder_plugins = new ArrayList();
	ArrayList plugins_list = Plugins.getPluginsList();
	for (int i = 0; i < plugins_list.size(); i++) {
	    Plugin plugin = (Plugin) plugins_list.get(i);
	    if (plugin.doesExplodeMetadataDatabases() == true && plugin.doesProcessFile(file)) {
		exploder_plugins.add(plugin);
	    }
	}

	return exploder_plugins;	
    }
    
    public boolean isFileExplodable(File file)
    {
	ArrayList plugins_list = Plugins.getPluginsList();
	for (int i = 0; i < plugins_list.size(); i++) {
	    Plugin plugin = (Plugin) plugins_list.get(i);
	    if (plugin.doesExplodeMetadataDatabases() == true && plugin.doesProcessFile(file) == true) { 
		return true;
	    }
	}

	return false;
    }

    // Works with replace_srcdoc_with_html.pl
    public ArrayList getSrcReplacerPlugins(File file)
    {
	ArrayList srcreplacer_plugins = new ArrayList();
	ArrayList plugins_list = Plugins.getPluginsList();
	for (int i = 0; i < plugins_list.size(); i++) {
	    Plugin plugin = (Plugin) plugins_list.get(i);
	    if (plugin.doesReplaceSrcDocsWithHtml() == true && plugin.doesProcessFile(file)) {
		srcreplacer_plugins.add(plugin);
	    }
	}

	return srcreplacer_plugins;	
    }	

    // Works with replace_srcdoc_with_html.pl
    public boolean isFileSrcReplaceable(File file)
    {
	ArrayList plugins_list = Plugins.getPluginsList();
	for (int i = 0; i < plugins_list.size(); i++) {
	    Plugin plugin = (Plugin) plugins_list.get(i);
	   
	    if (plugin.doesReplaceSrcDocsWithHtml() == true && plugin.doesProcessFile(file) == true) { 
		return true;
	    }
	}

	return false;
    }	

    /** Method to assign a plugin
     * @param plugin the Plugin to assign
     */
    private void assignPlugin(Plugin plugin) {
      if(plugin.getName().equals(StaticStrings.RECPLUG_STR) || plugin.getName().equals(StaticStrings.ARCPLUG_STR) || plugin.getName().equals(StaticStrings.METADATAXMLPLUG_STR)) {
	    addAfter(plugin, separator_plugin); // Adds after separator
	} else {
	    addBefore(plugin, separator_plugin);
	}
    }


    /** Destructor. */
    public void destroy()
    {
	CollectionManager.removeCollectionContentsChangedListener(this);

	if (controls != null) {
	    controls.destroy();
	    controls = null;
	}
    }


    /** This function listens for new files being added to the collection and hints about suitable plugins. */
    public void fileAddedToCollection(File file)
    {
	// First check the plugins already assigned in the collection
	for (int i = 0; i < super.getSize(); i++) {
	    Plugin assigned_plugin = (Plugin) getElementAt(i);
	    if (assigned_plugin.isSeparator() == false && (assigned_plugin.doesProcessFile(file) == true || assigned_plugin.doesBlockFile(file) == true)) {
		// This file will be processed by an assigned plugin, so no suggestion is necessary
		DebugStream.println("Processed by assigned plugin: " + assigned_plugin);
		return;
	    }
	}

	// Next try the plugins NOT already assigned in the collection
	ArrayList suitable_plugins = new ArrayList();
	Object[] unassigned_plugins = getAvailablePlugins();
	for (int i = 0; i < unassigned_plugins.length; i++) {
	    Plugin unassigned_plugin = (Plugin) unassigned_plugins[i];
	    if (unassigned_plugin.doesProcessFile(file) == true) {
		DebugStream.println("Processed by unassigned plugin: " + unassigned_plugin);
		suitable_plugins.add(unassigned_plugin);
	    }
	}

	// If there appear to be no suitable plugins, warn the user about this and be done
	if (suitable_plugins.size() == 0) {
	    String[] args = new String[1];
	    args[0] = file.getName();
	    WarningDialog warning_dialog = new WarningDialog("warning.NoPluginExpectedToProcessFile", Dictionary.get("NoPluginExpectedToProcessFile.Title"), Dictionary.get("NoPluginExpectedToProcessFile.Message", args), null, false);
	    warning_dialog.display();
	    warning_dialog.dispose();
	    return;
	}

	// Generate a dialog 
	new PluginSuggestionPrompt(file.getName(), suitable_plugins);
    }


    /** Method to retrieve the control for this manager.
     * @return the Control
     */
    public Control getControls() {
	if(controls == null) {
	    // Build controls
	    controls = new PluginControl();
	}
	return controls;
    }


    /** Overrides getSize in DOMProxyListModel to take into account the row count modifier used to hide the last three rows in lower detail modes
     * @return an int indicating the number of rows in the model, or more correctly the desired number of rows to display
     */
    public int getSize() {
	int result = super.getSize();
	if(modify_row_count) {
	  result = result-(NUM_FIXED_PLUGINS+1);
	}
	return result;
    }

    /** Called when the detail mode has changed which in turn may cause several design elements to be available/hidden
     * @param mode the new mode as an int
     */
    public void modeChanged(int mode) {
	if(controls != null) {
	    ((PluginControl)controls).modeChanged(mode);
	}
    }    

    /** Method to move a plugin in the list order.
     * @param plugin the Plugin you want to move.
     * @param direction true to move the plugin up, false to move it down.
     * @param all true to move to move all the way, false for a single step.
     */
    // why are all the error notices there when the buttons are disabled is you cant move???
    private void movePlugin(Plugin plugin, boolean direction, boolean all) {
	// Can't ever move RecPlug or ArcPlug
      if(super.getSize() < (NUM_FIXED_PLUGINS+2)) {
	    //DebugStream.println("Not enough plugins to allow moving.");
	    return;
	}
	if(plugin.getName().equals(StaticStrings.ARCPLUG_STR) || plugin.getName().equals(StaticStrings.RECPLUG_STR) || plugin.getName().equals(StaticStrings.METADATAXMLPLUG_STR)) {
	    JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.Move.Fixed"), Dictionary.get("CDM.Move.Title"), JOptionPane.ERROR_MESSAGE);
	    return;
	}
	if(all) {
	    // Move to top
	    if(direction) {
		// Remove the moving plugin
		remove(plugin);
		// Retrieve the first plugin
		Plugin first_plugin = (Plugin) getElementAt(0);
		// Add the moving plugin before the first plugin
		addBefore(plugin, first_plugin);
		first_plugin = null;
	    }
	    else {
		// Remove the moving plugin
		remove(plugin);
		// Add the moving plugin before the separator
		addBefore(plugin, separator_plugin);
	    }
	}
	else {
	    // Try to move the plugin one step in the desired direction.
	    int index = indexOf(plugin);
	    ///ystem.err.println("Index of " + plugin + " = " + index);
	    if(direction) {
		index--;
		if(index < 0) {
		    String args[] = new String[2];
		    args[0] = Dictionary.get("CDM.PlugInManager.PlugIn_Str");
		    args[1] = plugin.getName();
		    JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.Move.At_Top", args), Dictionary.get("CDM.Move.Title"), JOptionPane.ERROR_MESSAGE);
		    return;
		}
		remove(plugin);
		add(index, plugin);
	    }
	    else {
		index++;
		Plugin next_plugin = (Plugin) getElementAt(index);
		if(next_plugin.isSeparator()) {
		    String args[] = new String[1];
		    args[0] = plugin.getName();
		    JOptionPane.showMessageDialog(Gatherer.g_man, Dictionary.get("CDM.Move.Cannot", args), Dictionary.get("CDM.Move.Title"), JOptionPane.ERROR_MESSAGE);
		    // Still not going to move RecPlug or ArcPlug.
		    return;
		}
		remove(plugin);
		add(index, plugin);
	    }
	}
    }

    /** We attempt to place the separator between the unfixed and the fixed plugins. Since we only know of two fixed plugins, we search for either of them, and place the separator before them.
     */
    private void placeSeparator() {
	///ystem.err.println("Placing separator.");
	int separator_index = super.getSize();
	if(separator_index > 0) { 
	    boolean found_fixed = false;
	    int index = separator_index - 1;
	    while(index > 0) {
		Plugin plugin = (Plugin) getElementAt(index);
		String name = plugin.getName();
		if(name.equals(StaticStrings.RECPLUG_STR) || name.equals(StaticStrings.ARCPLUG_STR) || name.equals(StaticStrings.METADATAXMLPLUG_STR)) {
		    found_fixed = true;
		    index--;
		}
		else {
		    if(found_fixed) {
			separator_index = index + 1;
			index = -1;
		    }
		    else {
			index--;
		    }
		}
		name = null;
		plugin = null;
	    }
	}
	Element element = CollectionConfiguration.createElement(StaticStrings.PLUGIN_ELEMENT);
	element.setAttribute(StaticStrings.TYPE_ATTRIBUTE, StaticStrings.SEPARATOR_ATTRIBUTE);
	element.setAttribute(StaticStrings.SEPARATOR_ATTRIBUTE, StaticStrings.TRUE_STR);
	separator_plugin = new Plugin(element, null);
	///atherer.println("Adding plugin separator at: " + separator_index);
	add(separator_index, separator_plugin);
    }

    /** This method removes an assigned plugin. I was tempted to call it unassign, but remove is more consistent. Note that there is no way to remove a plugin from the library.
     * @param plugin The <strong>Plugin</strong> to remove.
     */
    private void removePlugin(Plugin plugin) {
	remove(plugin);
  
    }


    /** Inform the model to hide/show the last four lines on the list.
     * @param modify_row_count true to hide the last four lines, false otherwise
     */
    private void setHideLines(boolean modify_row_count) {
	this.modify_row_count = modify_row_count;
	int original_size = super.getSize();
	if(modify_row_count) {
	  fireIntervalRemoved(this, original_size - (NUM_FIXED_PLUGINS+2), original_size - 1);
	}
	else {
	  fireIntervalAdded(this, original_size - (NUM_FIXED_PLUGINS+2), original_size - 1);
	}
    }

    /** Determine the current separator index. */
    private int findSeparatorIndex() {
	int separator_index = super.getSize() - 1;
	while(separator_index >= 0) {
	    Plugin search = (Plugin) getElementAt(separator_index);
	    if(search.isSeparator()) {
		return separator_index;
	    }
	    separator_index--;
	}
	return separator_index;
    }


    /** A class which provodes controls for assigned and editing plugins. */
    private class PluginControl
	extends JPanel
	implements Control {
	/** Button for adding plugins. */
	private JButton add = null;
	/** Button for configuring the selected plugin. */
	private JButton configure = null;
	/** Button to move an assigned plugin one position lower in the order. */
	private JButton move_down_button = null;
	/** Button to move an assigned plugin one position higher in the order. */
	private JButton move_up_button = null;
	/** Button to remove the selected plugin. */
	private JButton remove = null;
	/** A combobox containing all of the known plugins, including those that may have already been assigned. */
	private JComboBox plugin_combobox = null;
	/** The label next to the plugin combobox. */
	private JLabel plugin_label = null;
	/** The label above the assigned plugin list. */
	private JLabel plugin_list_label = null;
	/** A list of assigned plugins. */
	private JList plugin_list = null;
	/** The area where the add, configure and remove buttons are placed. */
	private JPanel button_pane = null;
	/** The region which divides the central portion of the view into list and controls */
	private JPanel central_pane = null;
	/** The area where movement buttons are placed. */
	private JPanel movement_pane = null;
	/** The small region containing the plugin combobox and its label. */
	private JPanel plugin_pane = null;
	/** The pane containing the assigned plugin list and its label. */
	private JPanel plugin_list_pane = null;

	/** Constructor.
	 */
	public PluginControl()
	{
	    // Create
	    add = new GLIButton(Dictionary.get("CDM.PlugInManager.Add"), Dictionary.get("CDM.PlugInManager.Add_Tooltip"));
	    
	    button_pane = new JPanel();
	    central_pane = new JPanel();
            button_pane.setComponentOrientation(Dictionary.getOrientation());
            central_pane.setComponentOrientation(Dictionary.getOrientation());
            
	    configure = new GLIButton(Dictionary.get("CDM.PlugInManager.Configure"), Dictionary.get("CDM.PlugInManager.Configure_Tooltip"));
	    configure.setEnabled(false);
	    
	    JPanel header_pane = new DesignPaneHeader("CDM.GUI.Plugins", "plugins");
	    move_up_button = new GLIButton(Dictionary.get("CDM.Move.Move_Up"), JarTools.getImage("arrow-up.gif"), Dictionary.get("CDM.Move.Move_Up_Tooltip"));
	    move_up_button.setEnabled(false);
	    
	    move_down_button = new GLIButton(Dictionary.get("CDM.Move.Move_Down"), JarTools.getImage("arrow-down.gif"), Dictionary.get("CDM.Move.Move_Down_Tooltip"));
	    move_down_button.setEnabled(false);
	    
	    movement_pane = new JPanel();
            movement_pane.setComponentOrientation(Dictionary.getOrientation());
            
	    PluginComboboxListener picl = new PluginComboboxListener();
	    plugin_combobox = new JComboBox(getAvailablePlugins());
	    plugin_combobox.setOpaque(!Utility.isMac());
	    plugin_combobox.setEditable(false);
            plugin_combobox.setComponentOrientation(Dictionary.getOrientation());
            
	    picl.itemStateChanged(new ItemEvent(plugin_combobox, 0, null, ItemEvent.SELECTED));

	    plugin_label = new JLabel(Dictionary.get("CDM.PlugInManager.PlugIn"));
	    plugin_label.setComponentOrientation(Dictionary.getOrientation());
            
	    plugin_list = new JList(model);
	    plugin_list.setOpaque(true);
	    plugin_list.setCellRenderer(new ListRenderer());
	    plugin_list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	    plugin_list.setComponentOrientation(Dictionary.getOrientation());
            
            plugin_list_label = new JLabel(Dictionary.get("CDM.PlugInManager.Assigned"));
	    //plugin_list_label.setHorizontalAlignment(JLabel.CENTER);
	    plugin_list_label.setOpaque(true);
	    plugin_list_label.setComponentOrientation(Dictionary.getOrientation());
            
	    plugin_list_pane = new JPanel();
            plugin_list_pane.setComponentOrientation(Dictionary.getOrientation());
            
	    plugin_pane = new JPanel();
	    plugin_pane.setOpaque(true);
            plugin_pane.setComponentOrientation(Dictionary.getOrientation());
            
	    remove = new GLIButton(Dictionary.get("CDM.PlugInManager.Remove"), Dictionary.get("CDM.PlugInManager.Remove_Tooltip"));
	    remove.setEnabled(false);
	    
	    // Listeners
	    add.addActionListener(new AddListener());
	    configure.addActionListener(new ConfigureListener());
	    MoveListener ml = new MoveListener();
	    move_down_button.addActionListener(ml);
	    move_down_button.addActionListener(CollectionDesignManager.all_change_listener);
	    move_up_button.addActionListener(ml);
	    move_up_button.addActionListener(CollectionDesignManager.all_change_listener);
	    plugin_combobox.addItemListener(picl);
	    remove.addActionListener(new RemoveListener());
	    remove.addActionListener(CollectionDesignManager.all_change_listener);
	    plugin_list.addMouseListener(new ClickListener());
	    plugin_list.addListSelectionListener(new ListListener());
	    picl = null;

	    // Layout
	    movement_pane.setBorder(BorderFactory.createEmptyBorder(0,2,0,0));
	    movement_pane.setLayout(new GridLayout(4,1));
	    movement_pane.add(move_up_button);
            JPanel tmp = new JPanel();
            tmp.setComponentOrientation(Dictionary.getOrientation());
	    movement_pane.add(tmp);
            tmp = new JPanel();
            tmp.setComponentOrientation(Dictionary.getOrientation());
	    movement_pane.add(tmp);
	    movement_pane.add(move_down_button);

	    plugin_list_pane.setLayout(new BorderLayout());
	    plugin_list_pane.add(plugin_list_label, BorderLayout.NORTH);
	    plugin_list_pane.add(new JScrollPane(plugin_list), BorderLayout.CENTER);
	    plugin_list_pane.add(movement_pane, BorderLayout.LINE_END);
	    modeChanged(Configuration.getMode()); // Whether the special plugins are hidden or not is mode dependant

	    plugin_label.setBorder(BorderFactory.createEmptyBorder(0,0,5,0));

	    plugin_pane.setBorder(BorderFactory.createEmptyBorder(5,0,5,0));
	    plugin_pane.setLayout(new BorderLayout(5,0));
	    plugin_pane.add(plugin_label, BorderLayout.LINE_START);
	    plugin_pane.add(plugin_combobox, BorderLayout.CENTER);

	    button_pane.setLayout(new GridLayout(1,3));
	    button_pane.add(add);
	    button_pane.add(configure);
	    button_pane.add(remove);

	    // Scope these mad bordering skillz.
	    JPanel temp = new JPanel(new BorderLayout());
	    temp.add(plugin_pane, BorderLayout.NORTH);
	    temp.add(button_pane, BorderLayout.SOUTH);
            temp.setComponentOrientation(Dictionary.getOrientation());
            
	    central_pane.setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
	    central_pane.setLayout(new BorderLayout());
	    central_pane.add(plugin_list_pane, BorderLayout.CENTER);
	    central_pane.add(temp, BorderLayout.SOUTH);

	    setBorder(BorderFactory.createEmptyBorder(0,5,0,0));
	    setLayout(new BorderLayout());
	    add(header_pane, BorderLayout.NORTH);
	    add(central_pane, BorderLayout.CENTER);

	    TestingPreparation.setNamesRecursively(this);
	}

	/** Method which acts like a destructor, tidying up references to persistant objects.
	 */
	public void destroy() {
	}

	/** This method is overridden to ensure the instructions are scrolled to top, before the super classes updateUI() is called.
	    no longer have instructions, do we still need updateUI???
	 */
	public void gainFocus() {
	    super.updateUI();
	}

	public void loseFocus() {
	}

	/** The current detail mode controls two aspects of plugin manager: whether the movement buttons are visible and whether the fixed position plugins Arc and RecPlug are in the list
	 * @param mode the current mode as an int, which can be matched against static ints in the Configuration class
	 */
	public void modeChanged(int mode) {
	    // First of all we clear the current selection, as there can be some serious problems if the user selects the plugins we're hiding, or had the last plugin selected before we unhid the last three
	    plugin_list.clearSelection();	 
	    plugin_combobox.setModel(new DefaultComboBoxModel(getAvailablePlugins()));
	    setHideLines(!(mode >= Configuration.EXPERT_MODE));

	    plugin_list_pane.updateUI();
	}


	private class AddListener
	    implements ActionListener
	{
	    public void actionPerformed(ActionEvent event)
	    {
		if (plugin_combobox.getSelectedItem() != null) {
		    // This must be done on a new thread for the remote building code
		    new AddPluginTask(plugin_combobox.getSelectedItem().toString()).start();
		}
	    }
	}


	private class AddPluginTask
	    extends Thread
	{
	    private String plugin_name;

	    public AddPluginTask(String plugin_name)
	    {
		this.plugin_name = plugin_name;
	    }

	    public void run()
	    {
		// Retrieve the plugin
		Plugin plugin = Plugins.getPlugin(plugin_name, true);
		if (plugin == null) {
		    System.err.println("Error: getPlugin() returned null.");
		    return;
		}

		// Create a new element in the DOM
		Element new_plugin_element = CollectionConfiguration.createElement(StaticStrings.PLUGIN_ELEMENT);
		new_plugin_element.setAttribute(StaticStrings.TYPE_ATTRIBUTE, plugin.getName());
		Plugin new_plugin = new Plugin(new_plugin_element, plugin);

		Gatherer.invokeInEDT_replacesProceedInCurrThread(
		 "PluginManager::AddPluginTask.run()",
		 Gatherer.SYNC,
		 new Runnable() {
		     public void run() {
			 
			 ArgumentConfiguration ac = new ArgumentConfiguration(new_plugin);
			 ac.addOKButtonActionListener(CollectionDesignManager.all_change_listener);
			 if (ac.display()) {
			     assignPlugin(new_plugin);
			     plugin_list.setSelectedValue(new_plugin, true);
			 }
		     }
		 });	    
	    }
	}


	/** Listens for double clicks upon the list and react as if the configure button was pushed. */
	private class ClickListener
	    extends MouseAdapter {
	    /** Called whenever the mouse is clicked over a registered component, we use this to chain through to the configure prompt.
	     * @param event A <strong>MouseEvent</strong> containing information about the mouse click.
	    */
	    public void mouseClicked(MouseEvent event) {
		if(event.getClickCount() == 2 ) {
		    if(!plugin_list.isSelectionEmpty()) {
			Plugin plugin = (Plugin) plugin_list.getSelectedValue();
			if(!plugin.isSeparator()) {
			    ArgumentConfiguration ac = new ArgumentConfiguration(plugin);
			    ac.addOKButtonActionListener(CollectionDesignManager.all_change_listener);
			    if (ac.display()) {
				refresh(plugin);
			    }
			    ac.destroy();
			    ac = null;
			}
		    }
		}
	    }
	}

	/** This class listens for actions upon the configure button in the controls, and if detected creates a new <strong>ArgumentConfiguration</strong> dialog box to allow for configuration.
	 * @see org.greenstone.gatherer.cdm.ArgumentConfiguration
	 */
	private class ConfigureListener
	    implements ActionListener {
	    /** Any implementation of <i>ActionListener</i> must include this method so that we can be informed when an action has occured on one of our target controls.
	     * @param event An <strong>ActionEvent</strong> containing information garnered from the control action.
	     */
	    public void actionPerformed(ActionEvent event) {
		if(!plugin_list.isSelectionEmpty()) {
		    Plugin plugin = (Plugin) plugin_list.getSelectedValue();
		    if(!plugin.isSeparator()) {
			ArgumentConfiguration ac = new ArgumentConfiguration(plugin);
			ac.addOKButtonActionListener(CollectionDesignManager.all_change_listener);
			if (ac.display()) {
			    refresh(plugin);
			}
			ac.destroy();
			ac = null;
		    }
		}
	    }
	}

  /** listens for changes in the list selection and enables the configure and remove buttons if there is a selection, disables them if there is no selection */
  private class ListListener
    implements ListSelectionListener {
    
    public void valueChanged(ListSelectionEvent e) {
      if (!e.getValueIsAdjusting()) { // we get two events for one change in list selection - use the false one (the second one)
        if (plugin_list.isSelectionEmpty()) {
          move_up_button.setEnabled(false);
          move_down_button.setEnabled(false);
          configure.setEnabled(false);
          remove.setEnabled(false);
        } else {
          Plugin selected_plugin = (Plugin) plugin_list.getSelectedValue();
          if(selected_plugin.isSeparator()) {
            move_up_button.setEnabled(false);
            move_down_button.setEnabled(false);
            configure.setEnabled(false);
            remove.setEnabled(false);
          } else {
            configure.setEnabled(true);
            String plugin_name = selected_plugin.getName();
            // Some buttons are only available for plugins other than ArcPlug and RecPlug
            if(plugin_name.equals(StaticStrings.ARCPLUG_STR) || plugin_name.equals(StaticStrings.RECPLUG_STR) || plugin_name.equals(StaticStrings.METADATAXMLPLUG_STR)) {
              move_up_button.setEnabled(false);
              move_down_button.setEnabled(false);
              remove.setEnabled(false);
            } 

            else {
              // don't let people remove special plugins such GreenstoneXMLPlug and GreenstoneMETSPlug,
              // unless they are in expert mode or above
              int mode = Configuration.getMode();
              for (int i=0; i<StaticStrings.KEEP_PLUG.length; i++) {
                if ((plugin_name.equals(StaticStrings.KEEP_PLUG[i])) &&
                  (mode < Configuration.EXPERT_MODE)) {
                  remove.setEnabled(false);
                  break;
                } else {
                  remove.setEnabled(true);
                }
              }
              
              // Move ups are only enabled if the selected plugin isn't already at the top
              Plugin first_plugin = (Plugin) getElementAt(0);
              if(!first_plugin.equals(selected_plugin)) {
                move_up_button.setEnabled(true);
              } else {
                move_up_button.setEnabled(false);
              }
              // And move downs are only allowed when the selected plugin isn't at an index one less than the separator line.
              int separator_index = findSeparatorIndex();
              int selected_index = plugin_list.getSelectedIndex();
              if(selected_index < separator_index - 1) {
                move_down_button.setEnabled(true);
              } else {
                move_down_button.setEnabled(false);
              }
            }
            selected_plugin = null;
            plugin_name = null;
          }
        }
      }
    }
  }

	/** A special list renderer which is able to render separating lines as well. */
	private class ListRenderer
	    extends DefaultListCellRenderer {
	    /** Return a component that has been configured to display the specified value. That component's paint method is then called to "render" the cell. If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size, this method is called to generate a component on which getPreferredSize  can be invoked.
	     * @param list - The <strong>JList</strong> we're painting.
	     * @param value - The value returned by list.getModel().getElementAt(index) as an <strong>Object</strong>.
	     * @param index - The cells index as an <i>int</i>.
	     * @param isSelected - <i>true</i> if the specified cell was selected.
	     * @param cellHasFocus - <i>true</i> if the specified cell has the focus.
	     * @return A <strong>Component</strong> whose paint() method will render the specified value.
	     * @see javax.swing.JList
	     * @see javax.swing.JSeparator
	     * @see javax.swing.ListModel
	     * @see javax.swing.ListSelectionModel
	     */
	    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
		Plugin plugin = (Plugin) value;
		if(plugin.isSeparator()) {
		    return separator;
		}
		else {
		    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
		}
	    }
	}


	/** Listens for actions apon the move buttons in the manager controls, and if detected calls the <i>movePlugin()</i> method of the manager with the appropriate details. */
	private class MoveListener
	    implements ActionListener {
	    /** Any implementation of <i>ActionListener</i> must include this method so that we can be informed when an action has occured on one of our target controls.
	     * @param event An <strong>ActionEvent</strong> containing information garnered from the control action.
	     */
	    public void actionPerformed(ActionEvent event) {
		if (!plugin_list.isSelectionEmpty()) {
		    Object object = plugin_list.getSelectedValue();
		    if (object instanceof Plugin) {
			Plugin plugin = (Plugin) object;
			if (event.getSource() == move_up_button) {
			    movePlugin(plugin, true, false);
			}
			else if (event.getSource() == move_down_button) {
			    movePlugin(plugin, false, false);
			}


			// Solving GLI bug: Moving a second instance of plugin with same name (e.g. a 2nd PDFPlugin)
			// will select the 1st one after a single move is done.
			// Cause: plugin_list.setSelectedValue(plugin, true); would call
			// org.greenstone.gatherer.cdm.Plugin.compareTo() to decide which plugin we mean to select.
			// But because Plugin.compareTo() is overriden to only compare getName() and not toString(),
			// so that the first matching plugin with the same plug name gets selected a.o.t the specific
			// instance we just moved, and because removing the override has at least one side-effect, that
			// of introducing an extra MetadataXMLPlugin each time the collection/config file is reloaded
			// (which possibly happens in org.greenstone.gatherer.greenstone.Plugins.java when plugins are
			// loaded), I'm leaving Plugin.compareTo() override as-is. There may be more side-effects.

			// Getting the index of the plugin that was selected before the move (but which gets automatically
			// deselected after the move) with the following code:
			//  int selectedIndex = plugin_list.getSelectedIndex();
			//  Plugin plugin = (Plugin)plugin_list.getModel().getElementAt(selectedIndex);
			// and then doing selectedIndex-- for move up or selectedIndex++ for a move down will also require
			// extra code changes: making movePlugin() return boolean to indicate if a move was successful.

			// So re-selecting the plugin just moved with setSelectedValue() doesn't work:
			// Plugin.compareTo() is used underneath and selects the first plugin by that name and ideal
			// solution of messing with compareTo() has any number of unintended, unwanted consequences.
			
			// Instead, let GLI's custom DOMProxyListModel.indexTo() calculate the new index of the plugin
			// that was selected for the move (and which gets automatically de-selected after the move).
			// Thus we can select that plugin again after the move by its new index calculated by GLI code:
			
			//plugin_list.setSelectedValue(plugin, true);
			
			int selectedIndex = indexOf(plugin); 
			if(selectedIndex >= 0 && selectedIndex < plugin_list.getModel().getSize()) {
			    plugin_list.setSelectedIndex(selectedIndex);
			    plugin_list.ensureIndexIsVisible(selectedIndex);
			}
		    }
		}
	    }
	}

	/** This listener reacts to changes in the current selection of the plugin combobox. */
	private class PluginComboboxListener
        implements ItemListener {
        /** When a user selects a certain plugin, update the tooltip to show the plugin description. */
        public void itemStateChanged(ItemEvent event) {
            if(event.getStateChange() == ItemEvent.SELECTED) {
                // Retrieve the selected plugin
                Object current_selection = plugin_combobox.getSelectedItem();
                // And reset the tooltip. If the plugin is null or is a string, then go back to the default message
                if(current_selection == null || current_selection instanceof String) {
		    plugin_combobox.setToolTipText(Dictionary.get("CDM.PlugInManager.PlugIn_Tooltip"));
                }
                else {
                    Plugin current_plugin = (Plugin) current_selection;
		    plugin_combobox.setToolTipText(Utility.formatHTMLWidth(current_plugin.getDescription(), 40));
                    current_plugin = null;
                }
                current_selection = null;
            }
        }
    }
	
  /** This class listens for actions upon the remove button in the controls, and if detected calls the <i>removePlugin()</i> method.
   */
  private class RemoveListener
    implements ActionListener {
    /** Any implementation of <i>ActionListener</i> must include this method so that we can be informed when an action has occured on one of our target controls.
     * @param event An <strong>ActionEvent</strong> containing information garnered from the control action.
     */
    public void actionPerformed(ActionEvent event) {
      int selected_index = plugin_list.getSelectedIndex();
      if(selected_index != -1) {
        Plugin selected_plugin = (Plugin) plugin_list.getSelectedValue();
        removePlugin(selected_plugin);
        selected_plugin = null;
        // Refresh the available plugins
        plugin_combobox.setModel(new DefaultComboBoxModel(getAvailablePlugins()));

        // Select the next plugin if available
        if(selected_index < plugin_list.getModel().getSize()) {
          // If the new selection is above the separator we can remove it
          if(selected_index < findSeparatorIndex()) {
            plugin_list.setSelectedIndex(selected_index);
            
            // don't let people remove special plugins such GAPlug an METSPlug,
            // unless they are in expert mode or above
            int mode = Configuration.getMode();
            for (int i=0; i<StaticStrings.KEEP_PLUG.length; i++) {
              String selected_plugin_name
                = ((Plugin)plugin_list.getSelectedValue()).getName();
              
              if (selected_plugin_name.equals(StaticStrings.METADATAXMLPLUG_STR)) {
                //this plug cannot be removed under any conditions.
                remove.setEnabled(false);
              }else if ((selected_plugin_name.equals(StaticStrings.KEEP_PLUG[i])) &&
                (mode < Configuration.EXPERT_MODE)) {
                remove.setEnabled(false);
                break;
              } else {
                remove.setEnabled(true);
              }
            }
          }
          // Otherwise select the first non-removable plugin
          else {
            plugin_list.setSelectedIndex(selected_index + 1);
            remove.setEnabled(false);
          }
        } else {
          remove.setEnabled(false);
        }
      } else {
        remove.setEnabled(false);
      }
    }
  }
    }
    

    private class PluginSuggestionPrompt
	extends ModalDialog
	implements ActionListener
    {
	private Dimension size = new Dimension(480, 240);
	private GComboBox suitable_plugins_combobox = null;
	private GLIButton add_button = null;
	private GLIButton ignore_button = null;

	public PluginSuggestionPrompt(String filename, ArrayList suitable_plugins)
	{
	    super(Gatherer.g_man, true);
	    setModal(true);
	    setSize(size);
	    setTitle(Dictionary.get("CDM.PluginManager.SuggestedPluginListTitle"));
            this.setComponentOrientation(Dictionary.getOrientation());
            
	    String[] args = new String[1];
	    args[0] = filename;

	    JTextArea instructions_textarea = new JTextArea(Dictionary.get("CDM.PluginManager.Plugin_Suggestion_Prompt", args));
	    instructions_textarea.setCaretPosition(0);
	    instructions_textarea.setEditable(false);
	    instructions_textarea.setLineWrap(true);
	    instructions_textarea.setRows(5);
	    instructions_textarea.setWrapStyleWord(true);
            instructions_textarea.setComponentOrientation(Dictionary.getOrientation());
            
	    JLabel suitable_plugins_label = new JLabel(Dictionary.get("CDM.PlugInManager.PlugIn"));
	    suitable_plugins_label.setBorder(BorderFactory.createEmptyBorder(0,0,5,0));
            suitable_plugins_label.setComponentOrientation(Dictionary.getOrientation());
            
	    suitable_plugins_combobox = new GComboBox(suitable_plugins);
	    suitable_plugins_combobox.setBackgroundNonSelectionColor(Configuration.getColor("coloring.editable_background", false));
	    suitable_plugins_combobox.setBackgroundSelectionColor(Configuration.getColor("coloring.collection_selection_background", false));
	    suitable_plugins_combobox.setTextNonSelectionColor(Configuration.getColor("coloring.workspace_tree_foreground", false));
	    suitable_plugins_combobox.setTextSelectionColor(Configuration.getColor("coloring.collection_selection_foreground", false));
            suitable_plugins_combobox.setComponentOrientation(Dictionary.getOrientation());
            
	    JPanel suitable_plugins_pane = new JPanel();
            suitable_plugins_pane.setComponentOrientation(Dictionary.getOrientation());
	    //suitable_plugins_pane.setBorder(BorderFactory.createEmptyBorder(5,0,5,0));
	    suitable_plugins_pane.setLayout(new BorderLayout(5,0));
	    suitable_plugins_pane.add(suitable_plugins_label, BorderLayout.LINE_START);
	    suitable_plugins_pane.add(suitable_plugins_combobox, BorderLayout.CENTER);

	    add_button = new GLIButton(Dictionary.get("CDM.PlugInManager.QuickAdd"), Dictionary.get("CDM.PlugInManager.Add_Tooltip"));
	    ignore_button = new GLIButton(Dictionary.get("CDM.PlugInManager.Ignore"), Dictionary.get("CDM.PlugInManager.Ignore_Tooltip"));
	    
	    add_button.addActionListener(this);
	    ignore_button.addActionListener(this);

	    JPanel button_pane = new JPanel();
	    button_pane.setLayout(new GridLayout(1,2,5,0));
	    button_pane.add(add_button);
	    button_pane.add(ignore_button);
            button_pane.setComponentOrientation(Dictionary.getOrientation());
            
	    JPanel controls_pane = new JPanel();
	    controls_pane.setBorder(BorderFactory.createEmptyBorder(5,0,0,0));
	    controls_pane.setLayout(new GridLayout(2,1,0,5));
	    controls_pane.add(suitable_plugins_pane);
	    controls_pane.add(button_pane);
            controls_pane.setComponentOrientation(Dictionary.getOrientation());
            
	    JPanel content_pane = (JPanel) getContentPane();
            content_pane.setComponentOrientation(Dictionary.getOrientation());
	    content_pane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
	    content_pane.setLayout(new BorderLayout());
	    content_pane.add(instructions_textarea, BorderLayout.CENTER);
	    content_pane.add(controls_pane, BorderLayout.SOUTH);

	    // Show
	    Dimension screen_size = Configuration.screen_size;
	    setLocation((screen_size.width - size.width) / 2, (screen_size.height - size.height) / 2);

	    TestingPreparation.setNamesRecursively(this);
	    setVisible(true);
	}


	public void actionPerformed(ActionEvent event)
	{
	    // Close the dialog
	    setVisible(false);

	    if (event.getSource() == add_button) {
		AddPluginWithoutConfigurationTask add_plugin_task = new AddPluginWithoutConfigurationTask(suitable_plugins_combobox.getSelectedItem().toString());
		add_plugin_task.start();

		// We have to wait for this task to complete before continuing, otherwise
		// we might offer to add the same plugin again before the task has completed
		try {
		    add_plugin_task.join();
		}
		catch (Exception exception) {
		    DebugStream.printStackTrace(exception);
		}
	    }
	}


	private class AddPluginWithoutConfigurationTask
	    extends Thread
	{
	    private String plugin_name;

	    public AddPluginWithoutConfigurationTask(String plugin_name)
	    {
		this.plugin_name = plugin_name;
	    }

	    public void run()
	    {
		// Retrieve the plugin
		Plugin plugin = Plugins.getPlugin(plugin_name, true);
		if (plugin == null) {
		    System.err.println("Error: getPlugin() returned null.");
		    return;
		}

		// Create a new element in the DOM
		Element new_plugin_element = CollectionConfiguration.createElement(StaticStrings.PLUGIN_ELEMENT);
		new_plugin_element.setAttribute(StaticStrings.TYPE_ATTRIBUTE, plugin.getName());
		Plugin new_plugin = new Plugin(new_plugin_element, plugin);

		// Just assign the plugin with no argument configuration
		assignPlugin(new_plugin);
		Gatherer.c_man.getCollection().cdm.save();
	    }
	}
    }


    /** Creates a list separator.
     * Found on Google Groups. Code courtesy of Paul Farwell.
     */
    private JPanel getSeparator() {
	// We put the separator inside a panel to control its appearance
	JPanel _sepPanel = new JPanel();
	_sepPanel.setOpaque(false);
	_sepPanel.setBorder(BorderFactory.createEmptyBorder(1, 3, 1, 3));
	_sepPanel.setLayout(new BoxLayout(_sepPanel, BoxLayout.Y_AXIS));
	_sepPanel.add(Box.createRigidArea(new Dimension(0, 4)));
	// We have to be a little careful here, as the default UI for separators under MacOS is a blank box. Instead we force a BasicUI look
	_sepPanel.add(new BasicSeparator());
	_sepPanel.add(Box.createRigidArea(new Dimension(0, 4)));
	return _sepPanel;
    }

    /** This class behaves just like a normal JSeparator except that, no matter what the current settings in the UIManager are, it always paints itself with BasicSeparatorUI. */
    private static class BasicSeparator
	extends JSeparator {

	private ComponentUI basic_ui;

	public BasicSeparator() {
	    super();
	    basic_ui = new BasicSeparatorUI();
	}

	public void paintComponent(Graphics g) {
	    if (basic_ui != null) {
		basic_ui.update(g, this);
	    }   
	}
    }
}
