import os
import sys

# TODO: improvement: extract tile from underlying file and use that as the link name
def generateHtmlIndex(dirPath):
	"""Index a directory and convert to html. 
	Each item in directory becomes a link in an ul list.
	
	"""
	
	# if dir_path relative then make absolute
	pathToUse = os.path.abspath(dirPath)
	
	# print '>> Generating HTML index of directory: ', pathToUse
	
	result = "<ul>\n" # string to hold the result
	
	for f in os.listdir(pathToUse):
		# add file to result if file and of correct type
		if os.path.isfile(os.path.join(pathToUse,f)) and fileTypeFilter(f):
			
			fn = fileNameToString(f)
			result += "\t<li>\n"
			result += "\t\t<a href='" + f + "'>" + fn + "</a>\n"
			result += "\t</li>\n"
	
	result += "</ul>"
	print result
	

## ****************************************************************************

def fileNameToString(fileName):
	"""Convert standardized file name to nice string.
	E.g. remove '_', trailing type name (e.g. .txt), etc
	"""
	
	result = fileName[0:fileName.rfind(".")]
	result = result.replace("_"," ")
	result = result.title()
	
	return result
	 
def fileTypeFilter(fileName):
	"""Returns true if file is of type from list false otherwise"""
	fileExtension = fileName[fileName.rfind("."):]
	fileTypeList = [ ".txt" , ".html" , ".xml" , ".htm", ".rtf", ".pdf" ]
	
	return (fileExtension in fileTypeList)
	
	
## ****************************************************************************
## TESTS
## ****************************************************************************
	
def generateHtmlIndexTest():
	dirPath = "test/dir_to_index"
	dirPath2 = "../generate_directory_index/test/dir_to_index"
	# print os.path.abspath(dirPath2)
	generateHtmlIndex(dirPath2)
	
## ****************************************************************************
	
def fileNameToStringTest():
	print fileNameToString("hello.xml")
	print fileNameToString("hello_world.xml")
	
def fileTypeFilterTest():
	file1 = "test.txt"
	file2 = "test.css"

	if not fileTypeFilter(file1):
		print "FAIL" + file1 + " rejected as valid file type"
	
	if fileTypeFilter(file2):
		print "FAIL" + file2 + " accepted as valid file type"
		
## ****************************************************************************		
## MAIN

if __name__ == "__main__":

	# print sys.argv[1]
	# generateHtmlIndexTest()
	
	# fileNameToStringTest()
	# fileTypeFilterTest()
	
	generateHtmlIndex(sys.argv[1])