#! /usr/bin/env python
#############################################################
#                                                           #
#   Author: Herve Menager                                   #
#   Organization:'Biological Software and Databases' Group, #
#                Institut Pasteur, Paris.                   #
#   Distributed under GPLv2 Licence. Please refer to the    #
#   COPYING.LIB document.                                   #
#                                                           #
#############################################################
import os
import mb_cgi
import Mobyle.MobyleJob 
from Mobyle.MobyleError import MobyleError
from Mobyle.Registry import registry
from Mobyle.JobFacade import JobFacade

def process(self):
    # program exists on the Server
    try:
        self.jobPID = self.request.getfirst('pid')
        self.rootJobPID = self.jobPID.split('::')[0]
        self.rootJobUrl = registry.getJobURL(self.rootJobPID)
        jf = JobFacade.getFromJobId(self.rootJobUrl)
        if len(self.jobPID.split('::'))==1:
            self.jobUrl = self.rootJobUrl
            if self.session and not(self.session.hasJob(self.jobUrl)):
                self.session.addJob(self.jobUrl)
        else:
            subjobs = jf.getSubJobs()
            self.jobUrl = [job['jobID'] for job in subjobs if job['jobPID']==self.jobPID][0]
        ownersList = self.jobPID.split('::')
        ownerPortals = [pid.split('.')[0] for pid in ownersList if len(pid.split('.'))==3]
        self.job = Mobyle.MobyleJob.MobyleJob(ID=self.jobUrl)
        jobName = self.job.jobState.getName().split('/')[-1][:-4]
        if len(ownerPortals)>0:
            jobName += '@'+ownerPortals.pop()
        self.title = "%s - %s" % (jobName, self.job.jobState.getDate())
    except Exception:
        if self.jobPID:
            self.error_title = "Job not found."
            self.error_msg = "The job %s cannot not be found." % self.jobPID
        else:
            self.error_title = "Job error."
            self.error_msg = "Error."
            mb_cgi.c_log.error(self.error_msg, exc_info=True)
        return
    self.xmlUrl = self.job.getJobid()+'/index.xml'
    isIE = (os.environ.get("HTTP_USER_AGENT", "unknown").find("MSIE")!=-1)
    self.xslPipe = [
                    (self.cfg.portal_path()+"/xsl/job.xsl",
                        {'jobPID':"'"+self.jobPID+"'",
                         'previewDataLimit':"'"+str(self.cfg.previewDataLimit())+"'",
                         'isIE':"'"+str(isIE)+"'"
                         }),
                    (self.cfg.portal_path()+"/xsl/remove_ns.xsl",{}) # remove xhtml namespace junk
                    ]
    

if __name__ == "__main__":
    il = mb_cgi.XSLCGI(processFunction=process,useSession=True)