import os
import re
# only for the tests
import sys
import shutil

def renameFiles(dirPath):
	"""Rename files (and directories) under dirPath
	"""
	
	# if dir_path relative then make absolute
	pathToUse = os.path.abspath(dirPath)
	
	for f in os.listdir(pathToUse):
		fullItemName = os.path.join(pathToUse,f)
		# if a dir need to recurse
		if not(os.path.isfile(fullItemName)):
			renameFiles( fullItemName )

		newName = standardizeName(f)
		
		newFullName = os.path.join(pathToUse, newName)
		os.rename(fullItemName,newFullName)
		

def standardizeName(oldName):
	"""Standardize a name (remove or convert all non-standard characters)"""
	newName = oldName
	newName = newName.replace(" ","_")
	# if lowercase followed by uppercase transform to lower_lower
	regEx = re.compile('([a-z])([A-Z])')
	newName = regEx.sub(r'\1_\2',newName) 

	newName = newName.lower()
	
	# do we do dashes??
	# what about . (except for last one) e.g. hello mr. jones.txt ??

	return newName

	
## ****************************************************************************
## TESTS
## ****************************************************************************
	
def renameFilesTest():
	dirPath = "testdata"
	tmpPath = "tmp"
	destPath = tmpPath + "/this iS a Very Silly Directory Name"
	if os.path.exists(tmpPath):
		shutil.rmtree("tmp")
		
	os.mkdir(tmpPath)
	os.mkdir(destPath)
	for f in os.listdir(dirPath):
		shutil.copy(os.path.join(dirPath,f),os.path.join(destPath,f))
	
	renameFiles(tmpPath)
	
	
## ****************************************************************************
	
def standardizeNameTest():
	nameIn = "The Man is Here.txt"
	nameOut = "the_man_is_here.txt"
	# print standardizeName(nameIn)
	if(nameOut != standardizeName(nameIn)):
		print "Error: expected name out does not equal name out"

	nameIn = "theManIsHERe.txt"
	nameOut = "the_man_is_here.txt"
	# print nameIn
	# print standardizeName(nameIn)
	if(nameOut != standardizeName(nameIn)):
		print "Error: expected name out does not equal name out"
	

## ****************************************************************************		
## MAIN

if __name__ == "__main__":
	"""
	Rename files and directories recursively under the directory specified in the argument
	"""
	

	# test
	#standardizeNameTest()
	renameFilesTest()

	#renameFiles(sys.argv[1])
