//
// MiscTree.Browser.m -- Category of MiscTree that allows a MiscTree to be
// 		a delegate for an NXBrowser
//		Written by Scott Anguish (c) 1994 by Scott Anguish.
//				Version 1.0.  All rights reserved.
//
//		This notice may not be removed from this source code.
//
//	This program is included in the MiscKit by permission from the author
//	and its use is governed by the MiscKit license, found in the file
//	"LICENSE.rtf" in the MiscKit distribution.  Please refer to that file
//	for a list of all applicable permissions and restrictions.
//	

#import <misckit/misckit.h>

@implementation MiscTree(Browser)

- returnSelectedNode:theBrowser
	{
	
		id	pathString;
		id	theNode;
		
		
		pathString=[self returnSelectedPath:theBrowser];
		theNode=[self pathToChild:pathString];
		[pathString free];
		return theNode;
	
	}

- returnSelectedPath:theBrowser
	{
	
		id	pathString;
		char path[MAXPATHLEN+1];
		const char *nodeName;
		
		
		nodeName = [[[theBrowser matrixInColumn:[theBrowser lastColumn]] selectedCell] stringValue];
		[theBrowser getPath:path toColumn:[theBrowser lastColumn]];
		
		pathString=[[MiscString alloc] initString:path];
		if (nodeName)
			{
				[pathString cat:"/"];
				[pathString cat:nodeName];
			}
		
		return pathString;
	
	}


- pathToChild:theString
	{
		return [self pathToChild:theString level:1];
	}

- labelString 
	{ 
		return label; 
	}

	
- pathToChild:theString level:(int)theLevel
	{
		id	pathPart;
		id	leaf;
		int	partCount;
		int	i;
			
		pathPart=[theString extractPart:theLevel useAsDelimiter:'/'];
		partCount=[theString numOfChar:'/'];
		
		for (i=0; i < [branches count]; i++)
			{
				leaf=[branches objectAt:i];
				if ([pathPart compareTo:[leaf labelString]]==0)
					{ // we found the string we are looking for
					if (theLevel==partCount) 
						{
							return leaf;
						}
						else
						{
							return ([leaf pathToChild:theString level:(theLevel+1)]);
						}
					}
			}
		return nil;
	
	
	}


- (int)browser:sender fillMatrix:matrix inColumn:(int)column
	{
		char	thePath[MAXPATHLEN+1];
		id	pathString;
		id	theNode,theLeaf;
		int	count,i;
		
		if (column==0)
			{
				theNode=self;
			}
				else
			{
				[sender getPath:thePath toColumn:column];
				pathString=[[MiscString alloc] initString:thePath];
				theNode=[self pathToChild:pathString];
			}
	
		count=[[theNode branches] count];
		[matrix renewRows:count+1 cols:1];
	
		for (i=0; i < count; i++)
			{
				theLeaf=[[theNode branches] objectAt:i];
				[[matrix cellAt:i :0] setStringValue:[theLeaf label]];
				[[matrix cellAt:i :0] setLoaded:YES];
				[[matrix cellAt:i :0] setLeaf:([[theLeaf branches] count]==0)];
			}
		return count;
	}

@end
