/**
 *############################################################################
 * A component of the Greenstone Librarian Interface, part of the Greenstone
 * digital library suite from the New Zealand Digital Library Project at the
 * University of Waikato, New Zealand.
 *
 * Author: Michael Dewsnip, NZDL Project, University of Waikato, NZ
 *
 * Copyright (C) 2006 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.file;

import java.awt.event.*;
import java.io.File;
import java.util.Enumeration;
import javax.swing.*;
import javax.swing.tree.TreePath;
import org.greenstone.gatherer.Configuration;
import org.greenstone.gatherer.DebugStream;
import org.greenstone.gatherer.Dictionary;
import org.greenstone.gatherer.Gatherer;
import org.greenstone.gatherer.gui.CreateShortcutPrompt;
import org.greenstone.gatherer.gui.tree.DragTree;


public class WorkspaceTree
    extends DragTree
    implements MouseListener
{
    static public final int LIBRARY_CONTENTS_CHANGED = 10;
    static public final int DOWNLOADED_FILES_CHANGED = 11;
    static public final int FOLDER_SHORTCUTS_CHANGED = 12;


    public WorkspaceTree()
    {
	super(WorkspaceTreeModel.getWorkspaceTreeModel(), true);
	addMouseListener(this);

	setBackgroundNonSelectionColor(Configuration.getColor("coloring.workspace_tree_background", false));
	setBackgroundSelectionColor(Configuration.getColor("coloring.workspace_selection_background", false));
	setTextNonSelectionColor(Configuration.getColor("coloring.workspace_tree_foreground", false));
	setTextSelectionColor(Configuration.getColor("coloring.workspace_selection_foreground", false));

	filter.setBackground(Configuration.getColor("coloring.workspace_heading_background", false));
	filter.setEditable(Configuration.getMode() > Configuration.LIBRARIAN_MODE);
    }


    public void addDirectoryMapping(String name, File file)
    {
	// Update the information stored in the user's configuration
	Configuration.addDirectoryMapping(name, file);

	// Now update the tree
	refresh(FOLDER_SHORTCUTS_CHANGED);
    }


    public boolean isDraggable()
    {
	return true;
    }


    public boolean isDroppable()
    {
	return false;
    }


    public void mouseClicked(MouseEvent event)
    {
	if (SwingUtilities.isRightMouseButton(event)) {
	    new WorkspaceTreeRightClickMenu(this, event);
	}
    }

    public void mouseEntered(MouseEvent event) { }

    public void mouseExited(MouseEvent event) { }

    public void mousePressed(MouseEvent event) { }

    public void mouseReleased(MouseEvent event) { }


    public void refresh(int refresh_reason)
    {
	DebugStream.println("WorkspaceTree::refresh()... ");

	// The method for displaying the tree has changed - redraw the tree
  	if (refresh_reason == DragTree.TREE_DISPLAY_CHANGED) {
  	    DebugStream.println("...Reason: tree display changed.");
  	    updateUI();
  	}

	// The loaded collection has changed - currently do nothing
	if (refresh_reason == DragTree.LOADED_COLLECTION_CHANGED) {
	    DebugStream.println("...Reason: loaded collection changed.");
	}

	// The collection's contents have changed - refresh collection's import folder
	if (refresh_reason == DragTree.COLLECTION_CONTENTS_CHANGED) {
	    DebugStream.println("...Reason: collection contents changed.");
	    String collection_import_directory_path = Gatherer.c_man.getCollectionImportDirectoryPath();
	    refreshEveryNodeShowingFolder(collection_import_directory_path);
	}

	// The collections in the library have changed - refresh the collect directory
	if (refresh_reason == WorkspaceTree.LIBRARY_CONTENTS_CHANGED) {
	    DebugStream.println("...Reason: library contents changed.");
	    String collect_directory_path = Gatherer.getCollectDirectoryPath();
	    refreshEveryNodeShowingFolder(collect_directory_path);
	    WorkspaceTreeModel.refreshGreenstoneCollectionsNode();
	}

	// The downloaded files have changed - refresh that node
	if (refresh_reason == WorkspaceTree.DOWNLOADED_FILES_CHANGED) {
	    DebugStream.println("...Reason: downloaded files changed.");
	    WorkspaceTreeModel.refreshDownloadedFilesNode();
	}

	// The folder shortcuts have changed - refresh only them
	if (refresh_reason == WorkspaceTree.FOLDER_SHORTCUTS_CHANGED) {
	    DebugStream.println("...Reason: folder shortcuts changed.");
	    WorkspaceTreeModel.refreshFolderShortcuts();
	}
    }


    private void refreshEveryNodeShowingFolder(String folder_path_str)
    {
	// Search through the expanded tree paths, checking if any show the given folder
	TreePath tree_root_path = new TreePath(getModel().getRoot());
	Enumeration expanded_tree_paths = getExpandedDescendants(tree_root_path);
	while (expanded_tree_paths.hasMoreElements()) {
	    TreePath expanded_tree_path = (TreePath) expanded_tree_paths.nextElement();
	    WorkspaceTreeNode tree_node = (WorkspaceTreeNode) expanded_tree_path.getLastPathComponent();

	    File tree_node_file = tree_node.getFile();
	    if (tree_node_file == null) {
		continue;
	    }

	    // Get the path of the open tree node
	    String tree_node_path_str = tree_node_file.toString();
	    if (!tree_node_path_str.endsWith(File.separator)) {
		tree_node_path_str = tree_node_path_str + File.separator;
	    }

	    // If the specified folder is open, it must be refreshed
	    if (tree_node_path_str.equals(folder_path_str)) {
		System.err.println("Must refresh node " + tree_node_path_str + "!");
		((WorkspaceTreeModel) getModel()).refresh(expanded_tree_path);
	    }
	}
    }


    public void removeDirectoryMapping(WorkspaceTreeNode target)
    {
	// Update the information stored in the user's configuration
	Configuration.removeDirectoryMapping(target.toString());

	// Update tree
	refresh(FOLDER_SHORTCUTS_CHANGED);
    }


    public String toString()
    {
	return "Workspace";
    }


    /** When a user right-clicks within the workspace and collection trees they are presented with a small popup menu of context based options. This class provides such functionality.
     */
    private class WorkspaceTreeRightClickMenu
	extends JPopupMenu
	implements ActionListener
    {
	/** The tree over which the right click action occurred. */
	private WorkspaceTree workspace_tree = null;
	/** The tree nodes selected when the right click action occurred. */
	private TreePath[] selection_paths = null;
	/** The file record over which the right click action occurred. */
	private WorkspaceTreeNode node = null;

	private JMenuItem create_shortcut = null;
	private JMenuItem delete_shortcut = null;
	private JMenuItem collapse_folder = null;
	private JMenuItem expand_folder = null;
	private JMenuItem explode_metadata_database = null;
	private JMenuItem delete = null;
	private JMenuItem metaaudit = null;
	private JMenuItem new_folder = null;
	private JMenuItem new_dummy_doc = null;
	private JMenuItem open_externally = null;
	private JMenuItem rename = null;
	private JMenuItem replace = null;


	private WorkspaceTreeRightClickMenu(WorkspaceTree workspace_tree, MouseEvent event)
	{
	    super();
	    this.workspace_tree = workspace_tree;

	    // Note we have to use setImmediate() with the set selction paths
	    // otherwise the selection doesn't get updated until after the 
	    // popup comes up.

	    // the right click position
	    TreePath right_click_path = workspace_tree.getPathForLocation(event.getX(), event.getY());
	    if (right_click_path == null) {
		// user has clicked outside of the tree, clear the selection
		selection_paths = null;
		workspace_tree.setImmediate(true);
		workspace_tree.clearSelection();
		workspace_tree.setImmediate(false);
	    }
	    else {
		// Get the paths currently selected in the tree
		selection_paths = workspace_tree.getSelectionPaths();
		if (selection_paths == null) {
		    // nothing currently selected - we shift the selection to 
		    // the node that was right clicked on
		    selection_paths = new TreePath[1];
		    selection_paths[0] = right_click_path;
		    workspace_tree.setImmediate(true);
		    workspace_tree.setSelectionPath(right_click_path);
		    workspace_tree.setImmediate(false);
		}
		else if (selection_paths.length == 1 && ! selection_paths[0].equals( right_click_path)) {
		    workspace_tree.setImmediate(true);
		    workspace_tree.clearSelection();
		    workspace_tree.setSelectionPath(right_click_path);
		    workspace_tree.setImmediate(false);
		    selection_paths[0] = right_click_path;
		}
		else {
		    // we had multiply selected paths in the tree.
		    // if we clicked on one of those paths, then use all the 
		    // current selection, otherwise clear the selection and 
		    // select the one we right clicked on
		    boolean clicked_in_selection = false;
		    for (int i = 0; i < selection_paths.length; i++) {
			if (selection_paths[i].equals(right_click_path)) {
			    clicked_in_selection = true;
			    break;
			}
		    }
		    if (!clicked_in_selection) {
			// want the tree to update right away
			workspace_tree.setImmediate(true);
			workspace_tree.clearSelection();
			workspace_tree.setSelectionPath(right_click_path);
			workspace_tree.setImmediate(false);
			selection_paths = new TreePath[1];
			selection_paths[0] = right_click_path;
		    }
		}
	    }
	    
	    // Create an appropriate context menu, based on what is selected
	    buildContextMenu(selection_paths);

	    // Show the popup menu on screen
	    show(workspace_tree, event.getX(), event.getY());
	}


	private void buildContextMenu(TreePath[] selection_paths)
	{
	    // If nothing is selected, no options are available...
	    if (selection_paths == null) {
		return;
	    }

	    // Only meta-audit and delete are available if multiple items are selected...
	    if (selection_paths.length > 1) {
		return;
	    }

	    TreePath path = selection_paths[0];
	    node = (WorkspaceTreeNode) path.getLastPathComponent();

	    // ---- Options for file nodes ----
	    if (node.isLeaf()) {
		// Open the file in an external program
		open_externally = new JMenuItem(Dictionary.get("Menu.Open_Externally"), KeyEvent.VK_O);
		open_externally.addActionListener(this);
		add(open_externally);

		return;
	    }

	    // ---- Options for folder nodes ----
	    // Collapse or expand, depending on current status
	    if (workspace_tree.isExpanded(path)) {
		collapse_folder = new JMenuItem(Dictionary.get("Menu.Collapse"), KeyEvent.VK_C);
		collapse_folder.addActionListener(this);
		add(collapse_folder);
	    }
	    else {
		expand_folder = new JMenuItem(Dictionary.get("Menu.Expand"), KeyEvent.VK_O);
		expand_folder.addActionListener(this);
		add(expand_folder);
	    }

	    // Create/remove shortcut option, for workspace tree only
	    if (workspace_tree == workspace_tree) {
		// The "built-in" folders can't be modified
		String node_name = node.toString();
		if (node_name.equals(Dictionary.get("Tree.World")) || node_name.equals(Dictionary.get("Tree.Root")) || node_name.equals(Dictionary.get("Tree.DownloadedFiles"))) {
		    return;
		}

		// You can unmap 1st level nodes
		WorkspaceTreeNode root = (WorkspaceTreeNode) workspace_tree.getModel().getRoot();
		if (root.getIndex(node) != -1) {
		    delete_shortcut = new JMenuItem(Dictionary.get("MappingPrompt.Unmap"), KeyEvent.VK_R);
		    delete_shortcut.addActionListener(this);
		    add(delete_shortcut);
		}
		// Or map any other level directories
		else {
		    create_shortcut = new JMenuItem(Dictionary.get("MappingPrompt.Map"), KeyEvent.VK_S);
		    create_shortcut.addActionListener(this);
		    add(create_shortcut);
		}
	    }
	}


	/** Called whenever one of the menu items is clicked, this method then causes the appropriate effect. */
	public void actionPerformed(ActionEvent event)
	{
  	    Object source = event.getSource();

	    // Create shortcut
	    if (source == create_shortcut) {
 		CreateShortcutPrompt csp = new CreateShortcutPrompt(workspace_tree, node.getFile());
 		csp.destroy();
	    }

	    // Delete shortcut
  	    else if (source == delete_shortcut) {
  		workspace_tree.removeDirectoryMapping(node);
  	    }

	    // Collapse folder
	    else if (source == collapse_folder) {
		workspace_tree.collapsePath(selection_paths[0]);
	    }

	    // Expand folder
	    else if (source == expand_folder) {
		workspace_tree.expandPath(selection_paths[0]);
	    }

	    // Open in external program
	    else if (source == open_externally) {
		Gatherer.f_man.openFileInExternalApplication(node.getFile());
	    }
  	}
    }
}
