#! /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 mb_cgi
import os
from lxml import etree

from Mobyle.JobState import url2path
from Mobyle.Registry import registry

graphml_file_name = ".workflow_template_graphml.xml"

def process( self ):
    if self.session:
        job_id = registry.getJobURL(self.request.getfirst('id'))
        user_name = self.request.getfirst('userName').strip()
        if(self.session.hasJob(job_id) and self.session.getJobUserName(job_id)!=user_name):
            self.session.renameJob(job_id,user_name)
            job_graphml_file_path = os.path.join(url2path(job_id), graphml_file_name)
            #modify user name in workflow graphml file if it exists
            if os.path.exists(job_graphml_file_path):
                # rename in the graphml file directly as well
                source_file = open(job_graphml_file_path, 'r')
                root_tree = etree.parse(source_file)
                source_file.close()
                graph = root_tree.find('graph')
                if graph.get('userName')!=user_name:
                    graph.set('userName', user_name)
                    wffile = open(job_graphml_file_path, 'w' )
                    wffile.write( etree.tostring(root_tree)) 
                    wffile.close()
            self.message = user_name


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