// Copyright 1997-1999 Omni Development, Inc.  All rights reserved.
//
// This software may only be used and reproduced according to the
// terms in the file OmniSourceLicense.html, which should be
// distributed with this project and can also be found at
// http://www.omnigroup.com/DeveloperResources/OmniSourceLicense.html.

#import "NSArray-OFExtensions.h"

#import <Foundation/Foundation.h>
#import <OmniBase/OmniBase.h>

#import "OFRandom.h"

RCS_ID("$Header: /Network/Developer/Source/CVS/OmniGroup/OmniFoundation/OpenStepExtensions.subproj/NSArray-OFExtensions.m,v 1.6 1999/03/30 21:25:42 kc Exp $")

@implementation NSArray (OFExtensions)

- (id)anyObject;
{
    return [self count] > 0 ? [self objectAtIndex:0] : nil;
}

- (NSArray *)elementsAsInstancesOfClass:(Class)aClass withContext:context;
{
    NSMutableArray *array;
    NSAutoreleasePool *pool;
    NSEnumerator *elementEnum;
    NSDictionary *element;

    // keep this out of the pool since we're returning it
    array = [NSMutableArray array];

    pool = [[NSAutoreleasePool alloc] init];
    elementEnum = [self objectEnumerator];
    while ((element = [elementEnum nextObject])) {
	id instance;

	instance = [[aClass alloc] initWithDictionary:element context:context];
	[array addObject:instance];

    }
    [pool release];

    return array;
}

- (id)randomObject;
{
    unsigned int count;

    count = [self count];
    if (!count)
	return nil;
    return [self objectAtIndex:OFRandomNext() % count];
}

- (int)indexOfString:(NSString *)aString;
{
    return [self indexOfString:aString options:0 range:NSMakeRange(0, [aString length])];
}

- (int)indexOfString:(NSString *)aString options:(unsigned)someOptions;
{
    return [self indexOfString:aString options:someOptions range:NSMakeRange(0, [aString length])];
}

- (int)indexOfString:(NSString *)aString options:(unsigned)someOptions range:(NSRange)aRange;
{
    NSObject *anObject;
    Class stringClass;
    unsigned int index;
    unsigned int objectCount;
    
    stringClass = [NSString class];
    objectCount = [self count];
    for (index = 0; index < objectCount; index++) {
	anObject = [self objectAtIndex:index];
	if ([anObject isKindOfClass:stringClass] && [aString compare:(NSString *)anObject options:someOptions range:aRange] == NSOrderedSame)
	    return index;
    }
    
    return NSNotFound;
}

- (NSMutableArray *)deepMutableCopy;
{
    NSMutableArray *ret;
    NSEnumerator *selfEnum;
    id anObject;

    ret = [[NSMutableArray alloc] initWithCapacity:[self count]];
    selfEnum = [self objectEnumerator];
    while ((anObject = [selfEnum nextObject])) {
        if ([anObject respondsToSelector:@selector(deepMutableCopy)])
            [ret addObject:[anObject deepMutableCopy]];
        else if ([anObject respondsToSelector:@selector(mutableCopy)])
            [ret addObject:[anObject mutableCopy]];
        else
            [ret addObject:anObject];
    }

    return ret;
}

@end
