//
//  KMHistoryStack.m
//  BathyScaphe
//
//  Created by 堀 昌樹 on 12/03/24.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "KMHistoryStack.h"

@implementation KMHistoryStack

- (id)init
{
	self = [super init];
	if(self) {
		stock = [[NSMutableArray alloc] init];
		position = NSNotFound;
	}
	return self;
}
- (void)dealloc
{
	[stock release];
	
	[super dealloc];
}

- (void)push:(id)anObject
{
	if(ignoreNextPush) {
		ignoreNextPush = NO;
		return;
	}
	
	if([stock containsObject:anObject]) {
		[anObject retain];
		[stock removeObject:anObject];
		[stock addObject:anObject];
		[anObject release];
		position = [stock indexOfObject:anObject];
		return;
	}
	NSUInteger count = [stock count];
	if(count != 0) {
		if(count - 1 > position) {
			for(NSUInteger i = count - 1 - position; i > 0; i--) {
				[stock removeLastObject];
			}
		}
	}
	if(position == NSNotFound) {
		position = 0;
	} else {
		position++;
	}
	[stock addObject:anObject];
}
- (void)removeObject:(id)anObject
{
	id obj = [stock objectAtIndex:position];
	if([obj isEqual:anObject]) {
		if(position == 0) {
			if([stock count] == 1) {
				position = NSNotFound;
			}
			[stock removeObject:anObject];
			return;
		}
	}
	[stock removeObject:anObject];
	position = [stock indexOfObject:obj];
}
- (BOOL)canBack
{
	if(position == NSNotFound) return NO;
	return position;
}
- (BOOL)canForward
{
	if(position == NSNotFound) return NO;
	return ([stock count] - 1 > position);
}
- (id)back
{
	if(![self canBack]) return nil;
	return [stock objectAtIndex:--position];
}
- (id)forward
{
	if(![self canForward]) return nil;
	return [stock objectAtIndex:++position];
}

- (void)ignoreNextPush
{
	ignoreNextPush = YES;
}

@end
