// COPYRIGHT (C) 1990-1999.  All Rights Reserved. - DATA.CPP
// Zinc Software Incorporated.  Pleasant Grove, Utah  USA
// May be freely copied, used and distributed.

#include "data.hpp"

SimpleDatabase::SimpleDatabase(int setRecordSize) :
	recordSize(setRecordSize), records(0), currentIndex(-1)
{
}

SimpleDatabase::~SimpleDatabase(void)
{
}

void SimpleDatabase::AddRecord(void *record, ZafOffset index)
{
	if (index < 0)
		Add(new RecordElement(record, recordSize));
	else
	{
		ZafElement *positionElement = First();
		while (positionElement && index-- > 0)
			positionElement = positionElement->Next();
		Add(new RecordElement(record, recordSize), positionElement);
	}

	records++;
}

void SimpleDatabase::DeleteRecord(ZafOffset index)
{
	ZafElement *element = First();
	while (element && index-- > 0)
		element = element->Next();

	if (element)
	{
		if (currentElement == element)
		{
			if (currentElement->Next())
				currentElement = currentElement->Next();
			else
			{
				currentElement = currentElement->Previous();
				currentIndex--;
			}
		}

		Subtract(element);
		delete element;
		records--;
	}
}

void SimpleDatabase::ModifyRecord(ZafOffset index, void *record)
{
	ZafElement *element = First();
	while (element && index-- > 0)
		element = element->Next();

	if (element)
		((RecordElement *)element)->SetRecord(record, recordSize);
}

int SimpleDatabase::CurrentRecord(void *record)
{
	if (record && currentElement)
		memcpy(record, ((RecordElement *)currentElement)->Record(), (size_t)recordSize);
	return ((int)currentIndex);
}

int SimpleDatabase::SeekNextRecord(void *record)
{
	if (currentElement->Next())
	{
		currentElement = currentElement->Next();
		currentIndex++;
	}

	return (CurrentRecord(record));
}

int SimpleDatabase::SeekPreviousRecord(void *record)
{
	if (currentElement->Previous())
	{
		currentElement = currentElement->Previous();
		currentIndex++;
	}

	return (CurrentRecord(record));
}

int SimpleDatabase::SeekRandomRecord(ZafOffset index, void *record)
{
	ZafOffset i = index;
	ZafElement *element = First();
	while (element && i-- > 0)
		element = element->Next();

	if (element)
	{
		currentElement = element;
		currentIndex = index;
	}

	return (CurrentRecord(record));
}

SimpleDatabase::RecordElement::RecordElement(void *setRecord, int recordSize)
{
	record = new char[recordSize];
	memcpy(record, setRecord, (size_t)recordSize);
}

SimpleDatabase::RecordElement::~RecordElement(void)
{
	delete []record;
}
