//
//  NSOutlineView-MEAdditions.m
//  Merlin
//
//  Created by Frank Illenberger on 01.06.05.
//  Copyright 2006 ProjectWizards, Melle, Germany. 
//

#import "NSOutlineView-PWExtensions.h"

@interface NSObject (PrivateAPI) 
- (id)observedObject;
@end

@implementation NSOutlineView (PWExtensions)

- (NSArray *)originalItemsForItems:(NSArray *)items
{
	NSMutableArray *result = [NSMutableArray array];
	int count = [items count];
	for(int index=0; index<count; index++)
	{
		id item = [items objectAtIndex:index];
		id original = [self originalItemForItem:item];
		if(original)
			[result addObject:original];
	}
	return result;
}

- (NSArray *)itemsForOriginalItems:(NSArray *)originalItems
{
	NSMutableArray *result = [NSMutableArray array];
	int count = [originalItems count];
	for(int index=0; index<count; index++)
	{
		id originalItem = [originalItems objectAtIndex:index];
		id item = [self itemForOriginalItem:originalItem];
		if(item)
			[result addObject:item];
	}
	return result;
}

- (NSArray *)originalItemsAtRowIndexes:(NSIndexSet *)indexes
{
	NSMutableArray *result = [NSMutableArray array];
	
	unsigned int index = [indexes firstIndex];
	while(index != NSNotFound)
	{
		id obj = [self originalItemAtRow:index];
		if(obj)
			[result addObject:obj];
		index = [indexes indexGreaterThanIndex:index];
	}
	return result;
}

- (id)originalItemAtRow:(int)row
{
	return [[self itemAtRow:row] representedObject];
}

- (int)rowForOriginalItem:(id)originalItem
{
	int numberOfRows = [self numberOfRows];
	for(int row=0; row<numberOfRows; row++)
		if([self originalItemAtRow:row] == originalItem)
			return row;
	return -1;
}

- (NSIndexSet *)indexSetForOriginalItems:(NSSet *)items
{
	NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
	int numberOfRows = [self numberOfRows];
	for(int row=0; row<numberOfRows; row++)
	{
		id originalItem = [self originalItemAtRow:row];
		if(originalItem && [items containsObject:originalItem])
			[indexSet addIndex:row];	
	}
	return indexSet;
}

- (id)itemForOriginalItem:(id)originalItem
{
	int row = [self rowForOriginalItem:originalItem];
	return [self itemAtRow:row];
}

- (id)originalItemForItem:(id)item
{
	int row = [self rowForItem:item];
	return [self originalItemAtRow:row];
}

@end
