#!/usr/bin/env python 
from optparse import OptionParser
from seqprep import slurmProcessRun, settings
from seqprep.processRun import processRun
from seqhub import hUtil, hSettings
import sys, os, re, time, traceback
import os.path as path
from seqhub.hUtil import intersect
from seqhub.hUtil import touch

def seqprepOnNew(argv):
    parser = OptionParser(usage="usage: %prog [options]")
    parser.add_option("-d","--dir", help="Set directory searched for new sequencing runs. Default: %default",
                      default=hSettings.PRIMARY_PARENT, action="store", dest="primaryParent")
    parser.add_option("-s","--slurm", help="Process new runs on cluster instead of locally. Default: %default",
                      default=False, action="store_true", dest="slurm")
    parser.add_option("-v","--verbose", help="Verbose mode. Default: %default",
                      default=False, action="store_true", dest="verbose")
    (options, args) = parser.parse_args(argv)
    verbose = options.verbose
    primaryParent = options.primaryParent

    if len(args) != 0:
        parser.error("Expected 0 input arguments, " + str(len(args)) + " provided. Use -h to see usage.")

    required = ["InterOp", "RunInfo.xml", "SampleSheet.csv", "RTAComplete.txt"]  #files that must be in run folder
    interopRequired = ["QMetricsOut.bin", "TileMetricsOut.bin"]  #files that must be in <run>/InterOp folder
    runParametersOptions = ["runParameters.xml", "RunParameters.xml"] #one of these must be in run folder
    for item in os.listdir(primaryParent):
        itemPath = path.join(primaryParent, item)
        runNameMatch = re.match('[0-9]{6}_[0-9A-Za-z]+_[0-9A-Za-z]+_[0-9A-Za-z]{10}$', item) #re.match matches from beginning of string
        if path.isdir(itemPath) and runNameMatch:
            runName = item
            runPath = itemPath
            runItems = os.listdir(runPath) #get list of directory contents
            #check that we haven't examined this run folder before, and then check that required files are present:
            if 'seqprep_seen.txt' not in runItems \
                    and 'seqprep_skip.txt' not in runItems \
                    and 'seq_skip.txt' not in runItems \
                    and len(intersect(runItems, required)) == len(required) \
                    and len(intersect(runItems, runParametersOptions)) == 1 \
                    and len(intersect(os.listdir(path.join(runPath, "InterOp")), interopRequired)) == len(interopRequired):
                if verbose: print "\nNew run: " + runName
                touch(path.join(runPath, "seqprep_seen.txt"))  #mark run as seen by seqprep

                #send notification email
                hUtil.email(hSettings.SEQTOOLS_USERS_EMAILS,"Found new run", "Processing:\n" + runName)

                #start seqprep for this run
                myArgs = [runName, "--primary", primaryParent]
                if verbose: myArgs.append("--verbose")
                if options.slurm:
                     logMsg = time.strftime("%c") + "  Running slurmProcessRun.slurmProcess() on " + runName + " with args: " + ' '.join(myArgs)
                     hUtil.append(logMsg, settings.LOGFILE, echo = verbose)
                     slurmProcessRun.slurmProcess(myArgs)
                else:
                     logMsg = time.strftime("%c") + "  Running processRun.process() on " + runName + " with args: " + ' '.join(myArgs)
                     hUtil.append(logMsg, settings.LOGFILE, echo = verbose)
                     processRun(myArgs)

if __name__ == "__main__":
    seqprepOnNew(sys.argv[1:])
