/** SGX

The   sss    gggg x   x   
     s      g      x x    Engine
      sss   g  gg   x
         s  g   g  x x          Copyright 1995-2008.
     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: 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()
{
	delete m_pFirstChild;
	delete m_pNextSibling;
}

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;
}

