/**
 *#########################################################################
 *
 * 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.LocalLibraryServer;
import org.greenstone.gatherer.collection.BasicCollectionConfiguration;
import org.greenstone.gatherer.file.WorkspaceTree;  // !!! Don't like this here
import org.greenstone.gatherer.remote.RemoteGreenstoneServer;
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"));
	
	confirmation = new JCheckBox(Dictionary.get("DeleteCollectionPrompt.Confirm_Delete"));
	details = new JTextArea(Dictionary.get("DeleteCollectionPrompt.No_Collection"));
	details.setEditable(false);
	details_label = new JLabel(Dictionary.get("DeleteCollectionPrompt.Collection_Details"));

	list = new JList();
	list_label = new JLabel(Dictionary.get("DeleteCollectionPrompt.Collection_List"));
	
	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
	JPanel list_pane = new JPanel(new BorderLayout());
	list_pane.add(list_label, BorderLayout.NORTH);
	list_pane.add(new JScrollPane(list), BorderLayout.CENTER);
	list_pane.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));

	JPanel details_pane = new JPanel(new BorderLayout());
	details_pane.add(details_label, BorderLayout.NORTH);
	details_pane.add(new JScrollPane(details), BorderLayout.CENTER);
	details_pane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

	JPanel central_pane = new JPanel(new GridLayout(2, 1));
	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.add(confirmation, BorderLayout.CENTER);
	confirmation_pane.setBorder(BorderFactory.createEmptyBorder(0,0,5,0));

	JPanel button_pane = new JPanel(new GridLayout(1, 2));
	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.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.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()) {
	    // 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], Utility.CONFIG_FILE);
		    if (config_file.exists()) {
			BasicCollectionConfiguration config = new BasicCollectionConfiguration(config_file);
			list_model.addElement(config);
			config = null;
		    }
		}
	    }
	}
	// Otherwise the collect directory doesn't actually exist, so there ain't much we can do.
    }

    /** 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()) {
		confirmation.setEnabled(true);
		collection = (BasicCollectionConfiguration) list.getSelectedValue();
		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 {
		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.
	    // !! This should all go into CollectionManager !!

	    // First we must release it from the local library
	    if (LocalLibraryServer.isRunning() == true) {
		LocalLibraryServer.releaseCollection(collection.getShortName());
	    }

	    if (Gatherer.isGsdlRemote) {
		RemoteGreenstoneServer.deleteCollection(collection.getShortName());
	    }

	    if (Gatherer.c_man.deleteCollection(collection.getShortName())) {
		// Refresh the collections shown in the workspace tree
		Gatherer.g_man.refreshWorkspaceTree(WorkspaceTree.LIBRARY_CONTENTS_CHANGED);

		if (Gatherer.c_man.getCollection() != null && collection.getShortName().equals(Gatherer.c_man.getCollection().getName())) {
		    current_coll_deleted = true;
		}
		list_model.removeElement(collection);

		resultPrompt(true);
		details.setText(Dictionary.get("DeleteCollectionPrompt.No_Collection"));
		confirmation.setEnabled(false);
		confirmation.setSelected(false);
		ok_button.setEnabled(false);
		collection = null;
	    }
	    else {
		resultPrompt(false);
	    }
	}
    }
}
