package leaf.ui;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TreeTools
{

	public static void refreshTree( JTree tree, DefaultMutableTreeNode node )
	{
		((DefaultTreeModel) tree.getModel()).nodeStructureChanged( node );
		for( int i = 0; i < tree.getRowCount(); ++i)
		{
			tree.expandPath( tree.getPathForRow( i ) );
		}
	}
	
	public static boolean userObjectExistsOn( Object object, DefaultMutableTreeNode on )
	{
		boolean result = false;
		if( object != null && on != null )
		{
			result = object.equals( on.getUserObject() );
			for( int i = 0; i < on.getChildCount() && !result; ++i )
			{
				result |= userObjectExistsOn( object, (DefaultMutableTreeNode) on.getChildAt( i ) );
			}
		}
		return result;
	}

	public static DefaultMutableTreeNode findNodeWithUserObject( Object object, DefaultMutableTreeNode on )
	{
		DefaultMutableTreeNode result = null;
		if( object != null && on != null )
		{
			result = object.equals( on.getUserObject() ) ? on : null;
			for( int i = 0; i < on.getChildCount() && result == null; ++i )
			{
				result = object.equals(((DefaultMutableTreeNode) on.getChildAt( i )).getUserObject()) ? (DefaultMutableTreeNode) on.getChildAt( i ) : findNodeWithUserObject( object, (DefaultMutableTreeNode) on.getChildAt( i ) );
			}
		}
		return result;
	}

	public static DefaultMutableTreeNode cloneFullNode( DefaultMutableTreeNode node )
	{
		DefaultMutableTreeNode result = (DefaultMutableTreeNode) node.clone();
		for( int i = 0; i < node.getChildCount(); ++i )
		{
			DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt( i );
			result.add( cloneFullNode(child) );
		}
		return result;
	}
	
	public static void merge( DefaultMutableTreeNode with, DefaultMutableTreeNode what )
	{
		for( int i = 0; i < what.getChildCount(); ++i )
		{
			DefaultMutableTreeNode child = (DefaultMutableTreeNode) what.getChildAt( i );
			DefaultMutableTreeNode exists = TreeTools.findNodeWithUserObject( child.getUserObject(), with );
			if( exists == null )
			{
				with.add( TreeTools.cloneFullNode( child ) );
			}
			else
			{
				merge( exists, child );
			}
		}
	}

	public static void removeAll( DefaultMutableTreeNode from, DefaultMutableTreeNode what )
	{
		for( int i = 0; i < what.getChildCount(); ++i )
		{
			DefaultMutableTreeNode child = (DefaultMutableTreeNode) what.getChildAt( i );
			removeAll( from, child );
		}
		DefaultMutableTreeNode exists = TreeTools.findNodeWithUserObject( what.getUserObject(), from );
		if( exists != null )
		{
			exists.removeFromParent();
		}
	}
	
}
