#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import nijmetrics
import os
			
if __name__ == '__main__':
	
	if '--help' in sys.argv:
		
		print "This script dumps a summary sheet of results of the NIJ experiment using PiAnoS 4."
		print ""
		print "Syntax:"
		print os.path.split(sys.argv[0])[1]+" DB_URL"
		print ""
		print "URLs have the form pgsql://user:password@host:port/dbname. Missing username/password/dbname will default to 'pianos', host to 'localhost' and port to '5432'. The pgsql:// can be omitted. The simplest form of the URL is therefore '/dbname' - which means 'pgsql://pianos:pianos@localhost:5432/dbname'."
		print ""
		print "Options:"
		print " -e PATTERN: filters results by exercise, applied using an SQL SIMILAR TO clause on the exercise names using PATTERN"
		print " -u PATTERN: filters results by user, applied using an SQL SIMILAR TO clause on the user names using PATTERN"
		print " -t FILE: tee (duplicate) the output to the specified logfile."
		sys.exit(0)
		
	if len(sys.argv) < 2:
		print "ERROR: you must specify the connection URL as first argument. Try --help"
		sys.exit(1)
		
	settings = {
		'db_url': sys.argv[1],
	}
	
	def getarg(opt, key):
		try:
			i = sys.argv.index(opt)
			if len(sys.argv) < i+1:
				print "ERROR: option %s requires an argument" % opt
				sys.exit(1)
			settings[key] = sys.argv[i+1]
		except ValueError:
			pass
			
	def getopt(opt, key):
		if opt in sys.argv:
			settings[key] = True
			
	getarg('-e', 'exfilter')
	getarg('-u', 'userfilter')
	getarg('-t', 'tee')
	
	with nijmetrics.Tee(settings['tee']):
		del settings['tee']
		app = nijmetrics.Summary(**settings)
		sys.exit(0 if app.run() else 1)
