package leaf.ui;

import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

import com.evolute.utils.ui.trees.TreeTools;

public class LeafTree extends JTree
{

	private static final long serialVersionUID = 1L;
	
	private final List<Object> expandedNodes = new LinkedList<Object>();
	
	public LeafTree(TreeModel model)
	{
		super(model);
	}
	
	public void saveExpansionState()
	{
		expandedNodes.clear();
		TreePath treePath = new TreePath(getRoot());
		savePath( treePath );
	}
	
	private DefaultMutableTreeNode getRoot()
	{
		return (DefaultMutableTreeNode) getModel().getRoot();
	}
	
	private void savePath( TreePath treePath )
	{
		if( treePath != null )
		{
			Enumeration<TreePath> expanded = getExpandedDescendants(treePath);
			if( expanded != null )
			{
				while( expanded.hasMoreElements() )
				{
					TreePath path = expanded.nextElement();
					if( path != null )
					{
						Object leaf = path.getLastPathComponent();
						if( leaf instanceof DefaultMutableTreeNode )
						{
							Object userObject = ((DefaultMutableTreeNode)leaf).getUserObject();
							if( userObject != null )
							{
								expandedNodes.add(userObject);
							}
						}
					}
					savePath(path);
				}
			}
		}
	}
	
	public void loadExpansionState()
	{
		for( Object userObject : expandedNodes )
		{
			TreeTools.expandNodeForObject( userObject, this );
		}
	}
	
}
