// Copyright 1997-2002 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 <OWF/OWObjectStreamCursor.h>

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

#import <OWF/OWAbstractObjectStream.h>

RCS_ID("$Header: /Network/Source/CVS/OmniGroup/Frameworks/OWF/Content.subproj/OWObjectStreamCursor.m,v 1.12 2002/03/09 01:53:49 kc Exp $")

@implementation OWObjectStreamCursor

// Init and dealloc

- initForObjectStream:(OWAbstractObjectStream *)anObjectStream;
{
    if (![super init])
	return nil;

    objectStream = [anObjectStream retain];
    hint = NULL;
    streamIndex = 0;

    return self;
}

- initFromCursor:(id)aCursor;
{
    return [self initForObjectStream:[aCursor objectStream]];
}

- (void)dealloc;
{
    [objectStream release];
    [super dealloc];
}

//

- (OWAbstractObjectStream *)objectStream;
{
    return objectStream;
}

- (unsigned int)streamIndex;
{
    return streamIndex;
}

- (id)readObject;
{
    if (abortException)
	[abortException raise];
    return [objectStream objectAtIndex:streamIndex++ withHint:&hint];
}

- (void)skipObjects:(int)count;
{
    if (abortException)
	[abortException raise];
    [self seekToOffset:count fromPosition:OWCursorSeekFromCurrent];
}

- (void)ungetObject:(id)anObject;
{
    if (abortException)
	[abortException raise];
    OBASSERT([objectStream objectAtIndex:(streamIndex - 1) withHint:&hint] == anObject);
    streamIndex--;
}

// OWCursor subclass

- (OWContentType *)contentType;
{
    return [objectStream contentType];
}

- (unsigned int)seekToOffset:(int)offset fromPosition:(OWCursorSeekPosition)position;
{
    if (abortException)
	[abortException raise];
    switch (position) {
        case OWCursorSeekFromCurrent:
            streamIndex += offset;
            break;
        case OWCursorSeekFromEnd:
            streamIndex = [objectStream objectCount] - offset;
            break;
        case OWCursorSeekFromStart:
            streamIndex = offset;
            break;
    }
    return streamIndex;
}

// NSCopying protocol

- copyWithZone:(NSZone *)zone
{
    OWObjectStreamCursor *copyOfSelf;

    copyOfSelf = [[[self class] allocWithZone:zone] initForObjectStream:objectStream];
    copyOfSelf->streamIndex = streamIndex;
    return copyOfSelf;
}

// Debugging

- (NSMutableDictionary *)debugDictionary;
{
    NSMutableDictionary *debugDictionary;

    debugDictionary = [super debugDictionary];
    if (objectStream)
	[debugDictionary setObject:objectStream forKey:@"objectStream"];
    [debugDictionary setObject:[NSString stringWithFormat:@"%d", streamIndex] forKey:@"streamIndex"];

    return debugDictionary;
}

@end
