#! /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 Mobyle.MobyleJob 
from Mobyle.MobyleError import NoSpaceLeftError, UserValueError
from  Mobyle.Classes.DataType import DataTypeFactory
from Mobyle.Service import MobyleType

def process( self ):
    try:
        jobId = self.request.getfirst('job')
        resultId = self.request.getfirst('safeFileName')
        producerJob = Mobyle.MobyleJob.MobyleJob(ID=jobId)
        parameterName = self.request.getfirst('parameter')
        datatype_class = self.request.getfirst('datatype_class')
        datatype_superclass = self.request.getfirst('datatype_superclass','')
        format = self.request.getfirst('format','')
        biotypes = self.request.getlist('biotypes')
        df = DataTypeFactory()
        if (datatype_superclass==''):
            dt = df.newDataType(datatype_class)
        else:
            dt = df.newDataType(datatype_superclass, datatype_class)
        mt = MobyleType(dt,bioTypes=biotypes)
        if format:
            mt.setDataFormat(format)
        safeFileName = self.session.addData( resultId , mt, producer = producerJob , inputModes = ['result'], producedBy = jobId)
        if self.request.has_key('userName'):
            self.session.renameData(safeFileName,self.request.getfirst('userName'))
    except NoSpaceLeftError, e:
        mb_cgi.c_log.info("NoSpaceLeftError while bookmarking " + resultId + " - error: " +  str(e))
        self.jsonMap['errormsg'] = str(e)
    except UserValueError, e:
        mb_cgi.c_log.info("UserValueError while bookmarking " + resultId + " as a " + str(mt) + " - error: " +  str(e))        
        self.jsonMap['errormsg'] = str(e)        
    else:
        self.jsonMap['safeFileName'] = safeFileName
        self.jsonMap['inputModes'] = self.session.getData(safeFileName).get('inputModes')

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