/**
 *#########################################################################
 *
 * 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.net.*;
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.collection.CollectionManager;
import org.greenstone.gatherer.file.WorkspaceTree;  // !!! Don't like this here
import org.greenstone.gatherer.util.ArrayTools;
import org.greenstone.gatherer.util.StaticStrings;
import org.greenstone.gatherer.util.Utility;

/** This class provides the functionality to delete current collections from the GSDLHOME/collect/ directory. 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.
 * @author John Thompson, Greenstone Digital Library, University of Waikato
 * @version 2.3
 */
public class DeleteCollectionPrompt
    extends ModalDialog {
    /** The currently selected collection for deletion. */
    private BasicCollectionConfiguration collection = null;
    /** The model behind the list. */
    private DefaultListModel list_model = null;
    /** A reference to ourself so any inner-classes can dispose of us. */
    private DeleteCollectionPrompt prompt = null;
    /** The close button, which exits the prompt without deleting anything. */
    private JButton close_button = null;
    /** The ok button which causes the selected collection to be deleted. */
    private JButton ok_button = null;
    /** The confirmation check box. */
    private JCheckBox confirmation = null;
    /** The label above details. */
    private JLabel details_label = null;
    /** The label above the list. */
    private JLabel list_label = null;
    /** The list of available collections. */
    private JList list = null;
    /** The text area used to display details about the collection selected. */
    private JTextArea details = null;
    /** A string array used to pass arguments to the phrase retrieval method. */
    private String args[] = null;

    private boolean current_coll_deleted = false;
    /** The size of the delete prompt screen. */
    public static final Dimension SIZE = new Dimension(500, 500);

    /** Constructor.
     */
    public DeleteCollectionPrompt() {
	super(Gatherer.g_man);
	close_button = new GLIButton(Dictionary.get("General.Close"), Dictionary.get("General.Close_Tooltip"));
	this.setComponentOrientation(Dictionary.getOrientation());
	confirmation = new JCheckBox(Dictionary.get("DeleteCollectionPrompt.Confirm_Delete"));
	confirmation.setComponentOrientation(Dictionary.getOrientation());
        details = new JTextArea(Dictionary.get("DeleteCollectionPrompt.No_Collection"));
        details.setComponentOrientation(Dictionary.getOrientation());
	details.setEditable(false);
	details_label = new JLabel(Dictionary.get("DeleteCollectionPrompt.Collection_Details"));
        details_label.setComponentOrientation(Dictionary.getOrientation());
        
	list = new JList();
        list.setComponentOrientation(Dictionary.getOrientation());
	list_label = new JLabel(Dictionary.get("DeleteCollectionPrompt.Collection_List"));
	list_label.setComponentOrientation(Dictionary.getOrientation());
        
	list_model = new DefaultListModel();
	ok_button = new GLIButton(Dictionary.get("DeleteCollectionPrompt.Delete"), Dictionary.get("DeleteCollectionPrompt.Delete_Tooltip"));
	
	prompt = this;
	setModal(true);
	setSize(SIZE);
	setTitle(Dictionary.get("DeleteCollectionPrompt.Title"));	        
        
	setJMenuBar(new SimpleMenuBar("deletingcollections")); 
	close_button.addActionListener(new CloseButtonListener());
	confirmation.addActionListener(new ConfirmationCheckBoxListener());
	confirmation.setEnabled(false);
	confirmation.setSelected(false);
	list.addListSelectionListener(new CollectionListListener());
	list.clearSelection();
	list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
	list.setModel(list_model);
	ok_button.addActionListener(new OKButtonListener());
	ok_button.setEnabled(false);
	scanForCollections();
        
    }

    /** Destructor. */
    public void destroy() {
	list_model.clear();
	list_model = null;
	close_button = null;
	confirmation = null;
	details = null;
	details_label = null;
	list = null;
	ok_button = null;
	prompt = null;
    }

    /** This method causes the modal prompt to be displayed. 
     * returns true if it has deleted the collection that is currently open */
    public boolean display() {
	// Central pane
        JScrollPane scrol_tmp;
	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);
        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 confirmation_pane = new JPanel(new BorderLayout());
        confirmation_pane.setComponentOrientation(Dictionary.getOrientation());
	confirmation_pane.add(confirmation, BorderLayout.CENTER);
	confirmation_pane.setBorder(BorderFactory.createEmptyBorder(0,0,5,0));

	JPanel button_pane = new JPanel(new GridLayout(1, 2));
        button_pane.setComponentOrientation(Dictionary.getOrientation());
	button_pane.add(ok_button);
	button_pane.add(close_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(confirmation_pane, BorderLayout.NORTH);
	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(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 current_coll_deleted;
    }


    /** Shows a delete 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) {
	args = new String[1];
	args[0] = collection.getName();
	if (success) {
	    JOptionPane.showMessageDialog(prompt,Dictionary.get("DeleteCollectionPrompt.Successful_Delete", args),Dictionary.get("DeleteCollectionPrompt.Successful_Title"),JOptionPane.INFORMATION_MESSAGE);
	}
	else {
	    JOptionPane.showMessageDialog(prompt,Dictionary.get("DeleteCollectionPrompt.Failed_Delete", args),Dictionary.get("DeleteCollectionPrompt.Failed_Title"),JOptionPane.WARNING_MESSAGE);
	}
    }

    /** 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 void scanForCollections() {
	// Start at the collect dir.
	File collect_directory = new File(Gatherer.getCollectDirectoryPath());
	if (collect_directory.exists()) {
	  loadCollectionConfigs(collect_directory);
	}
    }

  private void loadCollectionConfigs(File directory) {
    // For each child directory see if it contains an 
    // etc/collect.cfg file and if so try to load it..
    File collections[] = directory.listFiles();
    String file_name = (Gatherer.GS3)? Utility.CONFIG_GS3_FILE : Utility.CONFIG_FILE;
    ArrayTools.sort(collections);
    for(int i = 0; collections != null && i < collections.length; i++) {
      File collection_folder = collections[i];
      String collection_name = collection_folder.getName();
      if(collection_folder.isDirectory() && !collection_name.equals(StaticStrings.MODEL_COLLECTION_NAME)) {
	File config_file = new File(collection_folder, file_name);
	if (config_file.exists()) {
	  BasicCollectionConfiguration config = new BasicCollectionConfiguration(config_file);
	  if (config.getCollectGroup().equals("true")) {
	    loadCollectionConfigs(collection_folder);
	  } else {
            // if webswing, are we allowed to delete this coll?
            if (Gatherer.isWebswing) {
              if (Gatherer.webswingAuthenticator.canEditCollection(collection_name)) {
                list_model.addElement(config);
              }
            } else {
              list_model.addElement(config);
            }
	    config = null;
	  }
	}
      }
    }
  }
  

    /** A button listener implementation, which listens for actions on the close button and disposes of the dialog when detected. */
    private class CloseButtonListener 
	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) {
	    // Done
	    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) {
	    ok_button.setEnabled(false);
	    confirmation.setSelected(false);
	    if(!list.isSelectionEmpty()) {
		collection = (BasicCollectionConfiguration) list.getSelectedValue();

		String currentColName = (Gatherer.c_man.getCollection() == null) ? "" : Gatherer.c_man.getCollection().getName();
		if(!collection.getShortName().equals(currentColName)) { 
		    // the selected collection can only be deleted if it is NOT the collection that is currently open
		    confirmation.setEnabled(true);
		    confirmation.setToolTipText(null); // no tooltip
		    ok_button.setToolTipText(null);

		    args = new String[3];
		    args[0] = collection.getCreator();
		    args[1] = collection.getMaintainer();
		    args[2] = collection.getDescription();
		    details.setText(Dictionary.get("DeleteCollectionPrompt.Details", args));
		    details.setCaretPosition(0);
		} else { // trying to delete the collection that is open at present
		    // add a tooltip saying to the confirmation checkbox saying that the current collection can't be deleted 
		    String tooltip = Dictionary.get("DeleteCollectionPrompt.Cannot_Delete_Open_Collection_Tooltip", 
						    collection.getName());
		    confirmation.setToolTipText(tooltip);
		    ok_button.setToolTipText(tooltip);
		    // delete/ok button and confirmation checkbox should be disabled
		    ok_button.setEnabled(false);
		    confirmation.setEnabled(false);
		    confirmation.setSelected(false);
		}
	    }
	    else {
		confirmation.setEnabled(false);
		details.setText(Dictionary.get("DeleteCollectionPrompt.No_Collection"));
	    }
	}
    }

    /** A check box listener so we can tell if the user has confirmed the deletion */
    private class ConfirmationCheckBoxListener
	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) {
	    // OK button is only enabled if the confirmation check box is ticked
	    ok_button.setEnabled(confirmation.isSelected());
	}
    }

    /** The OK button listener implementation. */
    private class OKButtonListener 
	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.
	 * @see org.greenstone.gatherer.Configuration
	 * @see org.greenstone.gatherer.Gatherer
	 * @see org.greenstone.gatherer.util.Utility
	 */
	public void actionPerformed(ActionEvent event)
	{
	    // Delete the selected collection.
	    if (Gatherer.c_man.deleteCollection(collection.getShortName())) {
		// Refresh the collections shown in the workspace tree
		Gatherer.g_man.refreshWorkspaceTree(WorkspaceTree.LIBRARY_CONTENTS_CHANGED);

		if (collection.getShortName().equals(CollectionManager.getLoadedCollectionName())) {
		    current_coll_deleted = true;
		}
		list_model.removeElement(collection);

		if (!Configuration.fedora_info.isActive()) { // for fedora collections, delete in background
		    resultPrompt(true);
		}
		details.setText(Dictionary.get("DeleteCollectionPrompt.No_Collection"));
		confirmation.setEnabled(false);
		confirmation.setSelected(false);
		ok_button.setEnabled(false);
		collection = null;
	    }
	    else {
		resultPrompt(false);
	    }
	}
    }
}
