/**
 *#########################################################################
 *
 * 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.util;

import java.lang.Runnable;
import javax.swing.SwingUtilities;
import javax.swing.tree.*;
import org.greenstone.gatherer.DebugStream;
import org.greenstone.gatherer.metadata.FilenameEncoding;
import org.greenstone.gatherer.collection.CollectionTreeNode;
import org.greenstone.gatherer.file.FileSystemModel;

/** Due to the TreeModel objects not having any synchronization, certain assumptions, such as the model state remaining constant during a repaint, don't always hold - especially given that I'm changing the tree model on a different thread. In order to get around this I will use the latest swing paradigm wherein you flag a section of code to be executed by the AWT GUI Event queue, as soon as other gui tasks have finished. This way I shouldn't have tree redraws throwing NPEs because the array size of the children of a certain node has changed -while- the repaint call was made, i.e. repaint() calls getChildCount() = 13, removeNodeFromParent() called, repaint calls getChildAt(12) = ArrayIndexOutOfBoundsException. 
 * @author John Thompson, Greenstone Digital Library, University of Waikato
 * @version 2.3c
 */
public class SynchronizedTreeModelTools {
    /** Adds an insertNodeInto model update onto the AWT Event queue. This gets around the lack of synchronization illustrated above. */
    static final public Runnable insertNodeInto(DefaultTreeModel model, MutableTreeNode parent, MutableTreeNode target_node) {
	return insertNodeInto(model, parent, target_node, true);
    }

    static final public Runnable insertNodeInto(final DefaultTreeModel model, final MutableTreeNode parent, final MutableTreeNode target_node, final boolean wait_allowed) {
	final Runnable doInsertNodeInto = new Runnable() {
		public void run() {
		    ///ystem.err.print("Running task... ");
		    DebugStream.println("insertNodeInto(" + model + ", " + parent + ", " + target_node + ", " + wait_allowed);
		    int index = -1;
		    int pos = 0;
		    while(index == -1 && pos < parent.getChildCount()) {
			TreeNode node = parent.getChildAt(pos);
			int result = 0;
			///ystem.err.println("Compare " + target_node + " to " + node);
			if((target_node.isLeaf() && node.isLeaf()) || (!target_node.isLeaf() && !node.isLeaf())) {
			    result = target_node.toString().toLowerCase().compareTo(node.toString().toLowerCase());
			}
			else if(target_node.isLeaf()) {
			    result = 1;
			}
			else {
			    result = -1;
			}
			if(result > 0) {
			    ///ystem.err.println("Keep searching...");
			    pos++;
			}
			else {
			    ///ystem.err.println("Found!");
			    index = pos;
			}
		    }
		    if(index == -1) {
			index = parent.getChildCount();
		    }
		    model.insertNodeInto(target_node, parent, index);
		}
	    };
	///ystem.err.print("Queuing Task... ");
	try {
	    if(wait_allowed && !SwingUtilities.isEventDispatchThread()) {
		///ystem.err.print("In another thread - invoke and wait... ");
		SwingUtilities.invokeAndWait(doInsertNodeInto);
	    }
	    else {
		///ystem.err.print("In Event Thread or wait not allowed - invoke later... ");
		SwingUtilities.invokeLater(doInsertNodeInto);
	    }
	}
	catch (Exception exception) {
	    DebugStream.printStackTrace(exception);
	}
	///ystem.err.print("Added Task... ");
	return doInsertNodeInto;
    }


    /** Adds a removeNodeFromParent model update onto the AWT Event queue. This gets around the lack of synchronization illustrated above.
     * @param model The <strong>GTreeModel</strong> we want to remove the node from.
     * @param target_node The <strong>GTreeNode</strong> to remove.
     */
    static final public void removeNodeFromParent(final DefaultTreeModel model, final MutableTreeNode target_node) {
	///ystem.err.println("Remove " + target_node + " from parent in model " + model);
	final Runnable doRemoveNodeFromParent = new Runnable() {
		public void run() {
			// If we're dealing with a collection tree node, it may have 
			// gs.FilenameEncoding assigned, so we remove its entry from the map. 
			// Needs to be done here because the tree is constantly changing 
			// when nodes are being removed, renamed and deleted, and this 
			// affects lookup queries sent to the map. 
			// Don't need to do a recursive reset on this coltreenode, because 
			// Delete/Move/Rename FileJobs were created for *each* node			
			if(target_node instanceof CollectionTreeNode) {
				CollectionTreeNode colNode = (CollectionTreeNode)target_node;
				FilenameEncoding.map.remove(colNode.getURLEncodedFilePath());
			}
			
		    model.removeNodeFromParent(target_node);			
		}
	    };
	try {
	    //SwingUtilities.invokeLater(doRemoveNodeFromParent);
	    SwingUtilities.invokeAndWait(doRemoveNodeFromParent);
	}
	catch (Exception exception) {
	    DebugStream.printStackTrace(exception);
	}
	// If we've thrown an error because we tried to invoke the runnable task and wait, when we are in the AWTEvent thread already, then try agin but with an invoke later.
	catch (java.lang.Error error) {
	    if(error.toString().equals("java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread")) {
		SwingUtilities.invokeLater(doRemoveNodeFromParent);
	    }
	}
    }

    /** Can't use removeNodeFromParent(): it can only remove the most recently-added GLI
     * shortcut, not any shortcuts added before that. That's because target_node isn't
     * actually in the tree but a temporary, independent node whose shortcut (name field)
     * matches a shortcut in the tree, but the target_node is not actually pointing to
     * the same object as the equivalent node in the actual tree.
     * @param model The <strong>GTreeModel</strong> we want to remove the node from.
     * @param target_node A temporary <strong>GTreeNode</strong> whose equivalent in
     * the tree is to be removed.
     * @param root The <strong>GTreeNode</strong> we want to remove the shortcut node from.
     */
    static final public void removeShortcutFromRoot(final DefaultTreeModel model, final MutableTreeNode root, final MutableTreeNode target_node) {
	///ystem.err.println("Remove shortcut " + target_node + " from root " + root + " in model " + model);
	final Runnable doRemoveShortcutFromRoot = new Runnable() {
		public void run() {
		    // I think there are no shortcuts in CollectionTree
		    // so don't need to do any fileenconding stuff here
		    ((org.greenstone.gatherer.file.FileSystemModel)model).removeNodeFromRoot(target_node, root);
		}
	    };
	try {
	    if(!SwingUtilities.isEventDispatchThread()) {
		///ystem.err.print("In another thread - invoke and wait... ");
		SwingUtilities.invokeAndWait(doRemoveShortcutFromRoot);
	    }
	    else { // Copied from insertNodeInto, but why invokeLater when already on the EDT?
		SwingUtilities.invokeLater(doRemoveShortcutFromRoot);
	    }
	}
	catch (Exception exception) {
	    DebugStream.printStackTrace(exception);
	}
    }
}
