//
// C++ Implementation: directoryutil
//
// Description: 
//
//
// Author: The BibleTime team <info@bibletime.info>, (C) 2006
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include "directoryutil.h"

//TQt includes
#include <tqdir.h>

namespace util {

namespace filesystem {

void DirectoryUtil::removeRecursive(const TQString& dir) {
	tqWarning("removeRecursive(%s)", dir.latin1());
	if (dir == TQString())  {
		return;
	}
	
	TQDir d(dir);
	if (!d.exists()) {
		return;
	}

	TQFileInfo *fi = 0;
	
	//remove all files in this dir
	d.setFilter( TQDir::Files | TQDir::Hidden | TQDir::NoSymLinks );

	const TQFileInfoList *fileList = d.entryInfoList();
	TQFileInfoListIterator it_file( *fileList );
	while ( (fi = it_file.current()) != 0 ) {
		++it_file;

		tqDebug("Removing %s", fi->absFilePath().latin1() );
		d.remove( fi->fileName() ) ;
	}

	//remove all subdirs recursively
	d.setFilter( TQDir::Dirs | TQDir::NoSymLinks );
	const TQFileInfoList *dirList = d.entryInfoList();
	TQFileInfoListIterator it_dir( *dirList );
	
	while ( (fi = it_dir.current()) != 0 ) {
		++it_dir;

		if ( !fi->isDir() || fi->fileName() == "." || fi->fileName() == ".." ) {
			continue;
		}
		
		tqDebug("Removing dir %s", fi->absFilePath().latin1() );
		//d.remove( fi->fileName() ) ;

		removeRecursive( fi->absFilePath() );
	}

	d.rmdir(dir);
}

/** Returns the size of the directory including the size of all it's files and it's subdirs.
 */
unsigned long DirectoryUtil::getDirSizeRecursive(const TQString& dir) {
	tqWarning("Getting size for %s", dir.latin1());

	TQDir d(dir);
	if (!d.exists()) {
		return 0;
	}

	d.setFilter(TQDir::Files);
	
	unsigned long size = 0;
	
	const TQFileInfoList* infoList = d.entryInfoList();
	TQFileInfoListIterator it(*infoList);
	TQFileInfo* info = 0;
	while ((info = it.current()) != 0) {
		++it;

		size += info->size();
	}

	d.setFilter(TQDir::Dirs);
	const TQFileInfoList* dirInfoList = d.entryInfoList();
	TQFileInfoListIterator it_dir(*dirInfoList);
	while ((info = it_dir.current()) != 0) {
		++it_dir;
		
		if ( !info->isDir() || info->fileName() == "." || info->fileName() == ".." ) {
			continue;
		}

		size += getDirSizeRecursive( info->absFilePath() );
	}
	
	return size;
}


} //end of namespace util::filesystem

} //end of namespace util

