#include <malloc.h>
#include <string.h>
#include "file.h"
#include "diriter.h"

Directory::Directory(const char *directory)
{
	// Ensure we aren't moved to a position
	numEntries = 0;
	entries = NULL;
	
	// Enumerate through to grab directory contents
	char fileName[MAXPATHLEN];
	FileType fileType;
	File dir;
	
	dir.open(directory, "d");
	
	// Loop through and add all
	while(dir.findNextFile(fileName, fileType))
	{		
		if(strcmp(fileName, ".") == 0) { continue; }
		if(strcmp(fileName, "..") == 0) { continue; }
		
		// Are we interested in this one?
		if(fileType == FILE_DIRECTORY)
		{
			// Allocate room on the pointer array
			if(numEntries == 0)
			{
				numEntries = 1;
				entries = (char **)malloc(sizeof(char *));
			}
			else
			{
				numEntries++;
				entries = (char **)realloc(entries, sizeof(char *) * numEntries);
			}
			
			// Allocate room for an actual string and copy over
			entries[numEntries - 1] = (char *)malloc(strlen(fileName) + 1);
			memcpy(entries[numEntries - 1], fileName, strlen(fileName) + 1);
			
			strlwr(entries[numEntries - 1]);
		}
	}
	
	dir.close();
}

Directory::~Directory()
{
	// Kill contents
	if(entries)
	{
		for(int i = 0; i < numEntries; i++)
		{
			if(entries[i])
			{
				// Kill individual entry
				free(entries[i]);
			}
		}
		
		// Kill list of pointers
		free(entries);
	}
	
	// Ensure properly uninitialized
	entries = NULL;
}

const char *Directory::getNext(const char *entry)
{
	int curEntry = findEntry(entry);
	
	// No entry found
	if(curEntry == -1 ) { return NULL; }
	
	// No entry
	if((curEntry + 1) >= numEntries) { return NULL; }
	
	return entries[(curEntry + 1)];
}

const char *Directory::getPrev(const char *entry)
{
	int curEntry = findEntry(entry);
	
	// No entry found
	if(curEntry == -1 ) { return NULL; }
	
	// No entry
	if((curEntry - 1) < 0) { return NULL; }
	
	return entries[(curEntry - 1)];
}

int Directory::findEntry(const char *entry)
{
	// No entries?
	if(numEntries == 0) { return -1; }
	
	// sanitize input
	char fileName[MAXPATHLEN];
	strcpy(fileName, entry);
	strlwr(fileName);
	
	for(int i = 0; i < numEntries; i++)
	{
		// Found?
		if(strcmp(entries[i], fileName) == 0) { return i; }
	}
	
	// Nope :<
	return -1;
}
