//
//  OxNsTreeController.m
//  Flash2
//
//  Copyright 2008 Nicholas Matsakis. 
//  The code in thie file is released to the public under the
//  terms of the MIT License as described here:
//  http://www.opensource.org/licenses/mit-license.php
//

#import "OxNSTreeController.h"
#import "Ox.h"

@implementation NSTreeController (Oaxaca2)

- (id) selectedObject
{
    id selObjs = [self selectedObjects];
    if ([selObjs count] > 0)
        return [selObjs objectAtIndex:0];
    return nil;
}

- (NSIndexPath*) searchObject:(id)haystack forObject:(id)needle path:(NSIndexPath*)path
{
	if ([haystack isEqual:needle])
		return path;
	
	NSString *childrenKeyPath = [self childrenKeyPath];
	id children = [haystack valueForKeyPath:childrenKeyPath];
	int index = 0;
	for (id child in children) {
		NSIndexPath *childPath = [self searchObject:child forObject:needle path:[path indexPathByAddingIndex:index++]];
		if (childPath != nil)
			return childPath;
	}
	return nil;
}

/* Walks the graph to find the first path to the given object */
- (NSIndexPath*) firstPathToObject:(id)object
{	
	NSArray *roots = [self content];
	for (int i = 0; i < [roots count]; i++) {		
		NSIndexPath *path = [self searchObject:[roots objectAtIndex:i]
									 forObject:object
										  path:[NSIndexPath indexPathWithIndex:i]];
		if (path != nil)
			return path;
	}
	return nil;
}


@end
