#include <stdio.h>
#include <malloc.h>
#include "history.h"

History::History()
{
	// Ensure nothing in the history
	_pos = 0;
	_count = 0;
	
	_history = NULL;
}

History::~History()
{
	// Clear history if needed
	clear();
}
	
void History::clear()
{
	// Clear data
	if(_history)
	{
		free(_history);
	}
	
	_history = NULL;
	
	// Reset aux variables
	_pos = 0;
	_count = 0;
}

void History::add(int data)
{
	// Figure out if we need to allocate a first, or just reallocate
	if(!_history)
	{
		// Create
		_count = 1;		
		_history = (int *)malloc(_count * sizeof(int));
	}
	else
	{
		// Append
		_count++;		
		_history = (int *)realloc(_history, _count * sizeof(int));
	}
	
	// Always shift to the end because we have just chosen a new history position
	_pos = _count - 1;
	
	// Remember data
	_history[_pos] = data;
}

bool History::hasNext()
{
	// Are we not at the last history?
	return _pos < (_count - 1);
}

bool History::hasPrevious()
{
	// Are we not at the first history?
	return _pos > 0;
}

int History::getNext()
{
	// Bad request
	if(!_history) { return -1; }
	
	if(hasNext())
	{
		// Only return if we aren't the last item
		_pos++;
		
		return _history[_pos];
	}
	else
	{
		// Bad request
		return -1;
	}
}

int History::getPrevious()
{
	// Bad request
	if(!_history) { return -1; }
	
	if(hasPrevious())
	{
		// Only return if we aren't the last item
		_pos--;
		
		return _history[_pos];
	}
	else
	{
		// Bad request
		return -1;
	}
}
