#!/hive/groups/encode/dcc/bin/python
import sys, os, re, argparse, subprocess
from ucscgenomics import qa

def main():

	""" Run all the checks, print output"""

	parser = argparse.ArgumentParser(
        prog='qaChecks',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description='A series of checks for QA',
        epilog=
    """Examples:

qaChecks hg19 tableList
qaChecks hg19 tableList /path/to/trackDb.ra
qaChecks hg19 tableList ~/kent/src/hg/makeDb/trackDb/human/hg19/wgEncodeSydhTfbs.new.ra

    """
        )
	parser.add_argument('database', help='The database, typically hg19 or mm9')
	parser.add_argument('tableList', help='The file containing a list of tables')
	parser.add_argument('trackDb', nargs='?', default=0, help='The trackDb file to check')

	if len(sys.argv) == 1:
		parser.print_help()
		return

	args = parser.parse_args(sys.argv[1:])

	f = open(args.tableList, "r")
	lines = f.readlines()
	tables = set()
	for i in lines:
		tables.add(i.rstrip())

	output = []

	output.append("Test 1: Checking tables for existence of description in tableDescription")
	(tableDescOutput, noDescription) = qa.checkTableDescriptions(args.database, tables)
	output.extend(tableDescOutput)

	output.append("Test 2: Checking tables for missing indices")
	(tableIndexOut, missingIndex) = qa.checkTableIndex(args.database, tables)
	output.extend(tableIndexOut)

	output.append("Test 4: Checking tables for underscores in the name")
	(tableNameOut, badTableNames) = qa.checkTableName(tables)
	output.extend(tableNameOut)

	output.append("Test 5: Checking TrackDb.ra file for short and long label length")
	if args.trackDb:
		(labelOut, badLabels) = qa.checkLabels(args.trackDb)
		output.extend(labelOut)
	else:
		output.append("Skipped, no trackDb file given")
		output.append("")

	output.append("Test 6: Checking tables for coordinate errors")
	(coordsOut, badCoords) = qa.checkTableCoords(args.database, tables)
	output.extend(coordsOut)

	output.append("Test 7: Checking tables for positional errors (sort)")
	(posOut, badPos) = qa.positionalTblCheck(args.database, tables)
	output.extend(posOut)

	output.append("Test 8: Counting row per chromosomes per table")
	(countChromOut, tableCounts) = qa.countPerChrom(args.database, tables)
	output.extend(countChromOut)

	for i in output:
		print i
	

if __name__ == "__main__":
	main()

