import threading, popen2, tempfile, sys, time, os

class Job(threading.Thread):
    def __init__(self, startrow, endrow, targetdir=None, callback=None,
                 checkinterval=30, sublock=None, statlock=None, getlock=None):
        threading.Thread.__init__(self)
        self.startrow = startrow
        self.endrow = endrow
        self.targetdir = targetdir
        self.callback = callback
        self.checkinterval = checkinterval
        self.sublock = sublock
        self.statlock = statlock
        self.getlock = getlock
        self.jobfile = tempfile.mktemp()
        self.resource = None
        self.substate = None
        self.state = None
        self.setstate("STARTING")

    def setstate(self, newstate):
        self.state = newstate
        self.do_callback()
        
    def setsubstate(self, newstate):
        self.substate = newstate
        self.do_callback()
        
    def do_callback(self):
        if self.callback:
            self.callback(self)

    def xrsltemplate(self):
        return '''&(executable=runpov.sh)
(arguments=%s %s)
(stdout="pov.out")
(stderr="pov.err")
(gmlog="pov.log")
(cputime=5)
(jobname=povray-%s)
(runtimeenvironment=povray)
(inputfiles=(monolith.pov "")
            (front.png ""))
(outputfiles=(monolith-%s-%s.png ""))''' % (self.startrow, self.endrow,
					    self.startrow,
                                            self.startrow, self.endrow)

    def submit(self):
        self.setsubstate("NGSUBLOCKWAIT")
        self.sublock.acquire()
        p = popen2.Popen3("ngsub -o %s '%s'" % (self.jobfile,
                                                self.xrsltemplate()),
                          capturestderr=1)
        self.setsubstate("NGSUB")
        status = p.wait()
        self.sublock.release()
        self.setsubstate(None)
        if os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0:
            self.jobid = open(self.jobfile, "r").read().strip()
            self.outdir = self.targetdir + "/" + self.jobid.split("/")[-1]
            self.setstate("SUBMITTED")
        else:
            self.setstate("SUBMISSIONFAILED")

    def getjobstate(self):
        self.setsubstate("NGSTATLOCKWAIT")
        self.statlock.acquire()
        p = popen2.Popen3("ngstat -l -i %s" % self.jobfile, capturestderr=1)
        self.setsubstate("NGSTAT")
        p.wait()
        self.statlock.release()
        self.setsubstate(None)
        state = None
        for line in p.fromchild.readlines():
            line = line.strip()
            if line.startswith("Status:"):
                fields = line.split()
                state = fields[1]
                if state == "INLRMS:":
                    state = state + " " + fields[2]
            if line.startswith("Error: JOB FAILURE"):
                self.setsubstate("FAILED")
            if line.startswith("Cluster:"):
                fields = line.split()
                self.resource = fields[1]

        return state

    def babysit(self):
        while not self.state in ("FINISHED", "SUBMISSIONFAILED"):
            time.sleep(self.checkinterval)
            sys.stdout.flush()
            jobstate = self.getjobstate()
            if jobstate and jobstate != self.state:
                self.setstate(jobstate)

    def download(self):
        self.setsubstate("NGGETLOCKWAIT")
        self.getlock.acquire()
        if self.targetdir:
            p = popen2.Popen3("ngget -i %s -dir %s" % (self.jobfile,
                                                       self.targetdir),
                              capturestderr=1)
        else:
            p = popen2.Popen3("ngget -i %s" % self.jobfile, capturestderr=1)
        self.setsubstate("NGGET")
        self.setstate("DOWNLOADING")
        status = p.wait()
        self.getlock.release()
        self.setsubstate(None)
        if os.WIFEXITED(status) and os.WEXITSTATUS(status) == 0:
            self.setstate("DOWNLOADED")
        else:
            self.setstate("DOWNLOADFAILED")

    def run(self):
        self.submit()
        self.babysit()
        if self.state != "SUBMISSIONFAILED":
            self.download()
        self.setsubstate("DONE")
