#!/usr/bin/python

# script to get stats on number of returned WUs
from os.path import abspath, exists
from glob import glob

fahtoolspath=abspath("../modules/fah_adaptive_sampling/FAHTools/") 
server2dir=abspath(".")
SVr=""
serverBinary="" 
###################################################

import sys
sys.path.append( fahtoolspath )
from FAHTrajectory import *
from ProjectConfigurationFile import *
from FAHServer import *

import MySQLdb

def usage() :
	print "Usage: ./checkReturns.py <projnum> <db name>"
        sys.exit()

try : ( projectnumber, dbname ) =sys.argv[1:]
except : usage()

print "Connecting to db ..."
try : conn = MySQLdb.connect(host="vspmf92", user="server", db=dbname )
except: usage()
cursor = conn.cursor()	

print "Parsing server configuration ..."
server=FAHServer( server2dir, serverBinary, SVr=SVr )
availableProjects = server.projects 

try:
	currproj=availableProjects[ projectnumber ]
except KeyError :
	print "project '%s' not found" % projectnumber
else:
	print "reading '%s' ... " % currproj
	conf = ProjectConfigurationFile( currproj )

	nruns = conf.nruns 
	nclones = conf.nclones 

	run = 0
	while run < nruns :
		clone = 0
		while clone < nclones :
			xtclist = glob( "%s/RUN%d/CLONE%d/frame*.xtc" % ( conf.datapath, run, clone ) )

			nxtcs = len(xtclist)
			if nxtcs > 0:
				print "RUN%d/CLONE%d: found %d xtc files ..." % ( run,clone,nxtcs), 
				gen = 0
				while gen < nxtcs :
					testxtc = "%s/RUN%d/CLONE%d/frame%d.xtc" % ( conf.datapath, run,clone,gen )  
					if not exists( testxtc ):
						print "%s not found" % testxtc
						print "stopping trajectory"
						stopfile = "%s/RUN%d/CLONE%d/STOP" % ( conf.datapath, run,clone )
						file = open( stopfile, "w" )
						file.close()
						print "deleting from db ..."
						qexec = "delete from frames where run=%d and clone=%d and gen>=%d" % ( run,clone,gen )
						print "executing '%s'" % qexec
						cursor.execute( qexec )
						result = cursor.fetchall()
						print "cursor returned: ", result
						break
					gen += 1
				print
			clone +=1
		run += 1
