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

import sys
import nijmetrics
import os
import argparse
import pg
import re
import random

class Error(Exception):
	pass
	
def run(input, db_url, dry_run=True):
	
	if not os.path.isdir(input):
		raise Error("input path '%s' is not a valid directory" % input)
		
	users = {}
	try:
		db = nijmetrics.Database(db_url)
		db.connect()
		for user in db.query("SELECT id,username FROM person;"):
			users[user['id']] = user['username']
	except (ValueError,pg.InternalError),err:
		raise Error(str(err))
	
	matching, non_matching = [], []
	
	exp = re.compile(r'user_(\d+)')
	
	renames = []
	
	for filename in os.listdir(input):
		match = exp.search(filename)
		if match:
			matching.append(filename)
			userid = int(match.group(1))
			try:
				username = users[userid]
			except KeyError,err:
				raise Error("user ID %d was not found in the database" % userid)
			outname = exp.sub(username, filename)
			#print filename
			#print "  ->",outname
			renames.append((filename,outname))
		else:
			non_matching.append(filename)
			#print filename
	
	print "Found %d items, %d to rename, %d unmodified" % (len(matching)+len(non_matching), len(matching), len(non_matching))
	if dry_run:
		if renames:
			print "Showing up to 10 items (at random) from the list"
			random.shuffle(renames)
			for src,dst in renames[:10]:
				print src
				print "  ->",dst
			print "If you are satisfied with the results, use --real to actually perform the renaming"
		else:
			print "Nothing to do! Is your input path correct?"
		
	else:
		for src, dst in renames:
			fsrc = os.path.join(input, src)
			fdst = os.path.join(input, dst)
			os.rename(fsrc, fdst)
		print "Done !"
		
def main():
	description = "This script renames debug output files generated by 'show_nij_metrics.py metrics -d XXX', replacing the user ID pattern with the actual username (e.g. 'user383' instead of 'user_550'). It needs the path to the debug folder (the argument to 'show_nij_metrics -d') and the PiAnoS 4 database URL to use to perform the conversion. Note that the default action is to perform a dry run - use --real to actually perform the conversion."
	
	parser = argparse.ArgumentParser(description=description)
	parser.add_argument('input', metavar='DIRECTORY', help="Path to the files to be converted")
	parser.add_argument('db_url', metavar='URL', help="PiAnoS 4 database URL (e.g. '/pianos4' or 'pgsql://user@host/dbname')")
	parser.add_argument('--real', action="store_true", help="By default this script will do a dry-run (i.e. do nothing). Use this flag to actually perform the renaming, after you have carefully inspected the output of a first run.")

	args = parser.parse_args()
	
	try:
		run(args.input, args.db_url, not args.real)
		return 0
	except Error,err:
		print "ERROR:",err
		return 1
		
if __name__ == '__main__':
	sys.exit(main() or 0)
	