#!/usr/bin/env python
import sys, os, re
import time
import datetime
import logging
from watchdog.observers.polling import PollingObserver as Observer
from watchdog.events import FileSystemEventHandler
import threading, thread
import h5py
from Bio import SeqIO
from StringIO import StringIO
import MySQLdb
import subprocess
import string
import configargparse
from warnings import filterwarnings
import socket
import hashlib
import xmltodict

parser = configargparse.ArgParser(description='eboladb_squiggle_align: A program providing the ability to determine which region of the ebola genome and individual read is derived from.')
parser.add('-fasta', '--reference_fasta_file', type=str, dest='fasta', required=True, default=None, help="The fasta format file for the reference sequence for your organism.")
parser.add('-ids', nargs = '*', dest='ids',required=True, help = 'A list of start and stop positions for each amplicon from the reference genome')
parser.add('-w', '--watch-dir', type=str, required=True, default=None, help="The path to the folder containing the downloads directory with fast5 reads to analyse - e.g. C:\data\minion\downloads (for windows).", dest='watchdir')
args = parser.parse_args()


#########################################################

if __name__ == "__main__":
	
	try:	
		db = MySQLdb.connect(host=args.dbhost, user=args.dbusername, passwd=args.dbpass, port=args.dbport)
		cursor = db.cursor()

	except Exception, err:
		print >>sys.stderr, "Can't connect to MySQL: %s" % (err)
		sys.exit(1)

	if ( (args.ref_fasta is not False) and (args.batch_fasta is not False) ):
		print "Both --align-ref-fasta (-f) and --align-batch-fasta (-b) were set. Select only one and try again."
		sys.exit(1)
		
	if ( (args.last_align is not False) and (args.bwa_align is not False) ):
		print "Both --last-align-true (-last) and --bwa-align-true (-bwa) were set. Select only one and try again."
		sys.exit(1)
	
	if (args.ref_fasta is not False):
		process_ref_fasta(args.ref_fasta)
	
	comments['default']='No Comment'
	if (args.add_comment is True):
		comment=raw_input("Type comment then press Enter to continue : ")	
		comments['default']=comment

 	print "monitor started."
	try:
		event_handler = MyHandler()
		observer = Observer()
		observer.schedule(event_handler, path=args.watchdir, recursive=True)
		observer.start()
		while True:
			time.sleep(1)
			
	except (KeyboardInterrupt, SystemExit):
		print "stopping monitor."
		observer.stop()
		time.sleep(1)
		#if (dbname is not None):
		#	#print "dbname", dbname
		for name in dbcheckhash["dbname"].keys():
			dba = MySQLdb.connect(host=args.dbhost, user=args.dbusername, passwd=args.dbpass, port=args.dbport, db=name)
			cur = dba.cursor() 
			print "setting %s to an inactive run" % (name)
			sql = "UPDATE Gru.minIONruns SET activeflag='0' WHERE runname=\"%s\" " % (name)
			cur.execute(sql)
			dba.commit()

			runindex =dbcheckhash["runindex"][name]
			finish_time=time.strftime('%Y-%m-%d %H:%M:%S')
			comment_string = "minUp version %s finished" % (minup_version)
			sql= "INSERT INTO Gru.comments (runindex,runname,user_name,comment,name,date) VALUES (%s,'%s','%s','%s','%s','%s') " % (runindex,name,args.minotourusername,comment_string,args.dbusername,finish_time)
			cur.execute(sql)
			dba.commit()

			with open(dbcheckhash["logfile"][name],"a") as logfilehandle:
				logfilehandle.write("minup finished at:\t%s:\tset to inactive gracefully%s" % (finish_time, os.linesep) )
				logfilehandle.close()
			dba.close()
		
		print "finished."
		sys.exit(1)
	observer.join()
	sys.exit(1)

######################################################

