#!python
#coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os
dirpath = os.path.join(os.path.dirname(os.path.abspath(__file__)),"../")
sys.path.insert(0,dirpath)
from jbiot.subjobs.ossfy import ossfy
from jbiot.subjobs.dockersing import dockersing
from jbiot.subjobs.csub.csub_strip import stripcmd
from jbiot.subjobs.csub import csub_run 
from jbiot.subjobs.jblog import jblog
from jbiot.subjobs.jbmsg import jbmsg
from jbiot.subjobs.stopjobs import cstop
import threading
from jbiot.subjobs.deamon import deamon

def csub(cmd,dry,rerun,verbose,force,email,name):
    tasks = stripcmd(cmd)
    if dry:
        return
    for task in tasks:
        cmdfile = task[0]
        mem,cpu = task[1]
        fail = csub_run.main(cmdfile,mem,cpu,rerun,verbose)
        if fail:
            jblog("\033[1;31mcontain failure,job should be stopped...\033[0m")
            if not force:
                jbmsg(cmd,email,name)
                sys.exit(1)
            jblog( "\033[1;31mgo on execute cause force mode is set on...\033[0m")

def main(cmdfile,dryflag,email,name,docker=False,sing=False,rerun=False,verbose=False,force=False,timeout=-1):
    cmdfile = ossfy(cmdfile)
    if docker :
        cmdfile = dockersing(cmdfile,prefer="docker")
    if sing:
        cmdfile = dockersing(cmdfile,prefer="singularity")
   
    t = threading.Thread(target=csub,args=(cmdfile,dryflag,rerun,verbose,force,email,name) )
    t.start()
    if timeout == -1:
        t.join()
        jbmsg(cmdfile,email,name)
    else:
        t.join(timeout)
    if t.is_alive():
        jblog("\033[1;31m\nJob timeout...\033[0m")
        jbmsg(cmdfile,email,name)
        cstop()
        t._Thread__stop()


if __name__ == "__main__":

    from docopt import docopt

    usage = """
    Usage:
        csub [options] <cmdfile> 

    Description:
        csub is used to submit cmdfile to sge compute cluster.

    Options:
        -h --help                print this screen
        --dry                    all done but run script
        --rerun                  rerun the job from last failure point
        --force                  force run even error detected
        --verbose                verbose mode lot of information will print
        --with-docker            prefer to use docker when run cmd
        --with-singularity       prefer to user singularity when run cmd
        -e,--email=<email>       email of you want to remind of
        -n,--name=<job_name>     the name of this task.
        --timeout=<timeout>      maxium seconds to run this job [default: -1]
        -d,--deamon             run it in deamon way. also,will gene stopmyjob.sh in curdir
     """
    args = docopt(usage)
    cmdfile = args["<cmdfile>"]
    dryflag = args["--dry"]
    docker = args["--with-docker"]
    sing = args["--with-singularity"]
    email = args["--email"]
    name = args["--name"]
    verbose = args["--verbose"]
    force = args["--force"]
    rerun = args["--rerun"]
    timeout = int(args["--timeout"])
    d = args["--deamon"]
    if not d:
        main(cmdfile,dryflag,email,name,docker=docker,sing=sing,rerun=rerun,verbose=verbose,force=force,timeout=timeout)
    else:
        script = os.path.abspath(__file__)
        stopfile = os.path.join(os.path.dirname(os.path.abspath(__file__)),"stopmyjob")
        import sys
        newargs = []
        for item in sys.argv[1:]:
            if item == "-d":
                continue
            if item == "--deamon":
                continue
            newargs.append(item)
        argstr = " ".join(newargs)
        deamon(script,argstr,cmdfile,stopfile)
