#include "ArrayItemList.h"
#include <malloc.h>
#include <memory.h>

Array* newArrayItemList()
{
	int initialSize = 10;
	Array* newArr;
	newArr = (Array*)malloc(sizeof(Array));
	newArr->pData = (LocalCallStack**)malloc(initialSize * sizeof(LocalCallStack*));
	memset(newArr->pData, 0, initialSize * sizeof(LocalCallStack*));
	newArr->items = 0;
	newArr->reserved = initialSize;
	return newArr;
}

void growSize(Array *arr)
{
	int newSize = arr->reserved * 2;
	LocalCallStack ** newData;
	newData = (LocalCallStack**)malloc(newSize * sizeof(LocalCallStack*));
	memset(newData, 0, newSize * sizeof(LocalCallStack*));
	memcpy(newData, arr->pData, sizeof(LocalCallStack*) * arr->reserved);
	free(arr->pData);
	arr->pData = newData;
	arr->reserved = newSize;
}

void deleteArrayItem(Array* arr, int nLocalId)
{
	LocalCallStack * lcs = arr->pData[nLocalId];
	arr->pData[nLocalId] = 0;
	arr->items--;
	if(lcs)
		disposeLocalCallStack(lcs);
}

void addArrayItem(Array * arr, LocalCallStack *lcs, int index)
{
	arr->pData[index] = lcs;
	arr->items++;
}

int getAvailableIndex(Array* arr, int nThreadId, int * pLocalId, int *pRemoteId)
{
	int i, nFirstFreeIndex = -1;

	if(arr->reserved == arr->items)
	{
		growSize(arr);
		return arr->items;
	}

	for(i = 0; i < arr->reserved; i++)
	{
		LocalCallStack * item  = arr->pData[i];
		if(!item)
		{
			if(nFirstFreeIndex < 0)
				nFirstFreeIndex = i;
		}
		else if(item->nThreadId == nThreadId)
		{
			*pRemoteId = item->nRemoteId;
			*pLocalId = i;
		}
	}
	//this line should be never reached...
	return nFirstFreeIndex;
}

void disposeArray(Array* arr)
{
	free(arr->pData);
	free(arr);
}
