//
//  XTCommandHistory.m
//  TadsTerp
//
//  Created by Rune Berg on 25/06/14.
//  Copyright (c) 2014 Rune Berg. All rights reserved.
//

#import "XTStringUtils.h"
#import "XTCommandHistory.h"
#import "XTAllocDeallocCounter.h"


@interface XTCommandHistory ()

@property NSMutableArray *commands;

@property NSUInteger indexOfLastCommandRetrived;

@end


@implementation XTCommandHistory

static const NSUInteger NO_COMMAND_RETRIEVED_THIS_TURN = 99999999;

OVERRIDE_ALLOC_FOR_COUNTER
OVERRIDE_DEALLOC_FOR_COUNTER

- (id)init
{
	self = [super init];
	if (self != nil) {
		_commands = [NSMutableArray arrayWithCapacity:100];
		_indexOfLastCommandRetrived = NO_COMMAND_RETRIEVED_THIS_TURN;
		_maxCommandCount = 10000;
		_pruneCommandOverflowBy = 500;
	}
	return self;
}

- (void)appendCommand:(NSString *)command
{
	command = [XTStringUtils trimLeadingAndTrailingWhitespace:command];
	if (command != nil && command.length >= 1) {
		// It's a non-empty command...
		NSString *prevCmd = [self.commands lastObject];
		if (prevCmd == nil || ! [command isEqualTo:prevCmd]) {
			// ...and not a duplicate of the one just before
			[self.commands addObject:command];
			if (self.commands.count > self.maxCommandCount) {
				// Prune excess entries
				NSRange rangeToRemove = NSMakeRange(0, self.pruneCommandOverflowBy);
				[self.commands removeObjectsInRange:rangeToRemove];
			}
		}
		self.indexOfLastCommandRetrived = NO_COMMAND_RETRIEVED_THIS_TURN;
	}
}

- (NSString *)getPreviousCommand
{
	NSString *res = nil;
	if (self.commands.count >= 1) {
		if (self.indexOfLastCommandRetrived == NO_COMMAND_RETRIEVED_THIS_TURN) {
			self.indexOfLastCommandRetrived = self.commands.count - 1;
			res = self.commands[self.indexOfLastCommandRetrived];
		} else if (self.indexOfLastCommandRetrived >= 1) {
			self.indexOfLastCommandRetrived -= 1;
			res = self.commands[self.indexOfLastCommandRetrived];
		}
	}
	return res;
}

- (NSString *)getNextCommand
{
	NSString *res = nil;
	if (self.commands.count >= 1) {
		if (self.indexOfLastCommandRetrived < self.commands.count - 1) {
			self.indexOfLastCommandRetrived += 1;
			res = self.commands[self.indexOfLastCommandRetrived];
		}
	}
	return res;
}

- (BOOL)hasBeenAccessed
{
	BOOL res = (self.indexOfLastCommandRetrived != NO_COMMAND_RETRIEVED_THIS_TURN);
	return res;
}

- (void)resetHasBeenAccessed
{
	self.indexOfLastCommandRetrived = NO_COMMAND_RETRIEVED_THIS_TURN;
}

@end
