#!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.jbmsg import jbmsg
from jbiot.subjobs.alisub.checkbcs import checkbcs,checkdcs

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...")
    jbmsg(cmd,email,name)

def main(cmdfile,dryflag,email,name,rerun=False,verbose=False,force=False,timeout=-1):
    bcs =  checkbcs()
    dcs = checkdcs()
    if bcs and dcs:
        ftime = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))
        wdir = "oss://jbiobio/working/tmp/%s/" % ftime
        asub(cmdfile,dryflag,wdir,rerun,verbose,force,email,name) 


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:
        -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
        -e,--email=<email>       email of you want to remind of
        -w,--wechat=<name>       wechat name you want to send to
        -n,--name=<job_name>     the name of this task.
        --timeout=<timeout>      maxium seconds to run this job [default: -1]
    """
    args = docopt(usage)
    cmdfile = args["<cmdfile>"]
    dryflag = args["--dry"]
    email = args["--email"]
    wechat = args["--wechat"]
    name = args["--name"]
    verbose = args["--verbose"]
    force = args["--force"]
    rerun = args["--rerun"]
    timeout = args["--timeout"]
    main(cmdfile,dryflag,email,name,rerun=rerun,verbose=verbose,force=force,timeout=timeout)
    
