/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2009.
     ssss    gggg x   x         Steven Goodwin. All Rights Reserved.
    
This version has been released under the GNU Public License v2.0.

Please see the license files for details.

File: sgx/src/sgx/filesystem/fileentry.cpp

*/

#include "sgx/core/core.hpp"
#include "sgx/filesystem/filesystem.hpp"

CSGXFileEntry::CSGXFileEntry() : m_Data()
{
    m_pBlock = NULL;
    m_pFSDevice = NULL;
    m_pFirstChild = NULL;
    m_pNextSibling = NULL;
	m_pParent = NULL;
}

CSGXFileEntry::CSGXFileEntry(const sgxString &Name) : m_Data(Name)
{
    m_pBlock = NULL;
    m_pFSDevice = NULL;
    m_pFirstChild = NULL;
    m_pNextSibling = NULL;
	m_pParent = NULL;
}

CSGXFileEntry::~CSGXFileEntry()
{
}

void
CSGXFileEntry::releaseHierarchy()
{
CSGXFileEntry *pChild = m_pFirstChild;
CSGXFileEntry *pPrevious;

	while(pChild) {
		pPrevious = pChild;
		pChild->releaseHierarchy();
		pChild = pChild->m_pNextSibling;
		delete pPrevious;
	}
	m_pFirstChild = NULL;
}

tBOOL CSGXFileEntry::isFile()
{
    if (m_pBlock) {
        return true;
    }
    return false;
}

tBOOL CSGXFileEntry::isFolder()
{
    return !isFile();
}

void CSGXFileEntry::getFileNamePath(sgxString &filename) const {
	if (m_pParent == NULL) {
		filename += m_Data.m_Name;
		
	} else {
		m_pParent->getFileNamePath(filename);
		if (filename != "/") {	// stop // at start of filenames
			filename += "/";
		}
		filename += m_Data.m_Name;
	}
}


CSGXDeviceBlockState *CSGXFileEntry::open(const sgxString &access) {
	if (isFile()) {
		return m_pFSDevice->open(m_pBlock, access);
	}
	return NULL;
}

CSGXFileEntry *CSGXFileEntry::createNewDirectory(const sgxString &dirName) {
	if (isFolder()) {
		return m_pFSDevice->createNewDirectory(this, dirName);
	}
	return NULL;
}
	
CSGXFileEntry *
CSGXFileEntry::getChildFile(const tUINT32 idx) {
	if (isFolder()) {
		tUINT32 c = idx;
		CSGXFileEntry *pChild = m_pFirstChild;

		while(pChild) {
			if (pChild->isFile()) {
				if (c == 0) {
					return pChild;
				}
				--c;
			}
			
			pChild = pChild->m_pNextSibling;
		}
	}
	return NULL;
}

CSGXFileEntry *
CSGXFileEntry::getChildFolder(const tUINT32 idx) {
	if (isFolder()) {
		tUINT32 c = idx;
		CSGXFileEntry *pChild = m_pFirstChild;

		while(pChild) {
			if (pChild->isFolder()) {
				if (c == 0) {
					return pChild;
				}
				--c;
			}
			pChild = pChild->m_pNextSibling;
		}
	}
	return NULL;
}

tBOOL
CSGXFileEntry::removeChild(CSGXFileEntry *pChild) {
	CSGXFileEntry *pSearch = m_pFirstChild;
	CSGXFileEntry *pPrevious = NULL;

	while(pSearch) {
		if (pSearch == pChild) {
			if (pPrevious) {
				pPrevious->m_pNextSibling = pChild->m_pNextSibling;
			} else {
				m_pFirstChild = pChild->m_pNextSibling;
			}
			pChild->m_pNextSibling = NULL;
			return TRUE;
		}

		pSearch = pSearch->m_pNextSibling;
		pPrevious = pSearch;
	}
	return FALSE;
}

