/******************************************************************************
 jDirUtil.cc

	System independent directory utilities.

	Copyright © 1996 by John Lindal. All rights reserved.

 ******************************************************************************/

#include <jDirUtil.h>
#include <JString.h>
#include <limits.h>
#include <jAssert.h>

static const JCharacter* kTempDirPrefix = "temp_dir_";

/******************************************************************************
 JGetTempDirectoryName

	Returns a unique directory name for use in the specified directory.
	If path is empty, it uses the current working directory.

	We ignore the possibility of not finding a valid name because the file
	system will fill up long before we run out of possibilities.

 ******************************************************************************/

JString
JGetTempDirectoryName
	(
	const JCharacter* path
	)
{
	return JGetUniqueDirEntryName(path, kTempDirPrefix);
}

/******************************************************************************
 JGetUniqueDirEntryName

	Returns a unique name, starting with namePrefix, for use in the specified
	directory.  If path is empty, it uses the current working directory.

	We ignore the possibility of not finding a valid name because the file
	system will fill up long before we run out of possibilities.

 ******************************************************************************/

JString
JGetUniqueDirEntryName
	(
	const JCharacter* path,
	const JCharacter* namePrefix
	)
{
	assert( !JStringEmpty(namePrefix) );

	JString fullPath;
	if (JStringEmpty(path))
		{
		fullPath = JGetCurrentDirectory();
		}
	else
		{
		const JBoolean ok = JConvertToAbsolutePath(path, NULL, &fullPath);
		assert( ok );
		}

	const JString prefix = JCombinePathAndName(fullPath, namePrefix);

	JString name;
	for (JIndex i=1; i<=INT_MAX; i++)
		{
		name = prefix + JString(i,0);
		if (!JNameUsed(name))
			{
			break;
			}
		}
	return name;
}
