#! /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
from Mobyle.BMPSWorkflow import BMPSWorkflow

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)
        jobUserName = None
        serviceURL = self.job.jobState.getName()

        # computing service PID based on the URL of the service in the Job XML
        servicePID = serviceURL.split('/')[-1]
        # if this is a BMPS workflow
        if BMPSWorkflow.BMW_FOLDER in serviceURL:
            servicePID = BMPSWorkflow.PID_PREFIX + servicePID.replace(BMPSWorkflow.MOBYLEXML_SUFFIX,'')
        # if this is a portal level remove '.xml'
        else:
            servicePID = servicePID[:-4]
        # if this is a imported service
        if len(ownerPortals)>0:
            servicePID = ownerPortals[-1] + servicePID

        if self.session.hasJob(self.jobUrl):
            jobUserName = self.session.getJob(self.jobUrl).get('userName',None)
        if jobUserName:
            self.title = jobUserName
        else:
            jobName = serviceURL.split('/')[-1][:-4]
            if len(ownerPortals)>0:
                jobName += '@'+ownerPortals[-1]
            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
            mb_cgi.c_log.error(self.error_msg, exc_info=True)
        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)
    #servicePID = self.jobPID[:self.jobPID.rfind('.')]
    self.xslPipe = [
                    (self.cfg.portal_path()+"/xsl/job.xsl",
                        {'jobPID':"'"+self.jobPID+"'",
                         'servicePID':"'"+servicePID+"'",
                         '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)