#!python
#coding=utf-8
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os
import time
dirpath = os.path.join(os.path.dirname(os.path.abspath(__file__)),"../")
sys.path.insert(0,dirpath)
from jbiot.subjobs.dockersing import dockersing
from jbiot.subjobs.alisub.asub_strip import stripcmd
from jbiot.subjobs.alisub.task_bc_run import task_run
from jbiot.subjobs.jblog import jblog
from jbiot.subjobs.wdir import readwdir,setwdir
from jbiot.subjobs.jbmsg import jbmsg
from jbiot.subjobs.alisub.checkbcs import checkbcs,checkdcs
from jbiot.subjobs.stopjobs import alistop
import threading
from jbiot.subjobs.deamon import deamon

def asub(cmd,dry,wdir,rerun,verbose,force,email,name):
    tasks = stripcmd(cmd)
    if dry:
        return
    for task in tasks:
        cmdfile = task[0]
        cpu,mem,docker = task[1]
        fail = task_run(cmdfile,cpu,mem,wdir,docker,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("go execute cause force mode is set on...")

def main(cmdfile,dryflag,email,name,wdir,rerun=False,verbose=False,force=False,timeout=-1):
    bcs =  checkbcs()
    dcs = checkdcs()

    if bcs and dcs:
        if not wdir:
            wdir = readwdir()
        setwdir(wdir)
        t = threading.Thread(target=asub,args=(cmdfile,dryflag,wdir,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)
            alistop()
            t._Thread__stop()

if __name__ == "__main__":

    from docopt import docopt

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

    Descption:
        asub is used to submit cmdfile to aliyun batch compute service. 
        docker images should contained in cmdfile. cause cmd is running in docker enviroments
        if no docker image. cmdfile will use default docker image which is jbioi/alpine-dev:latest

    Options:
        --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
        -e,--email=<email>       email of you want to remind of
        -w,--wdir=<dirname>      oss working directory
        -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"]
    email = args["--email"]
    wdir = args["--wdir"]
    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,wdir,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)

