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

def process( self ):
    if(not(self.request.has_key('data_input_upload'))):
        self.jsonMap['errormsg'] = "Please specify a file to upload."
    else:
        if self.request["data_input_upload"].file is not None:
            fileContent = self.request["data_input_upload"].file.read()
            fileName = self.request["data_input_upload"].filename
        else:
            fileContent = self.request.getfirst("data_input_upload")
            fileName = self.request.getfirst("data_input_upload.name","unnamed data bookmark")        
        if self.request.getfirst("base64encoded")=="true":
            import base64
            fileContent = base64.decodestring(fileContent)
        datatype_class = self.request.getfirst('datatype_class')
        datatype_superclass = self.request.getfirst('datatype_superclass','')
        df = DataTypeFactory()
        if (datatype_superclass==''):
            dt = df.newDataType(datatype_class)
        else:
            dt = df.newDataType(datatype_superclass, datatype_class)
        mt = MobyleType(dt)
        mt.setDataFormat(self.request.getfirst('format'))
        try:
            if(fileContent==''):
                raise UserValueError(msg='empty file, please check your data')
            safeFileName = self.session.addData( fileName , mt, content = fileContent , inputModes = self.request.getfirst("inputMode","upload"))
            contentData = self.session.getContentData(safeFileName)
            if df.issubclass(mt.getDataType(),"Binary"):
                self.jsonMap['content'] = "Binary data..."
            else:
                self.jsonMap['headFlag'] = contentData[0]
                if(self.jsonMap['headFlag']=="HEAD"):
                    self.jsonMap['content'] = contentData[1][0:2000]
                else:
                    self.jsonMap['content'] = contentData[1]
        except UserValueError, e:
            mb_cgi.c_log.info("UserValueError while uploading " + fileName + " - error: " +  str(e))
            self.jsonMap['errormsg'] = str(e)
        except NoSpaceLeftError, e:
            mb_cgi.c_log.info("NoSpaceLeftError while uploading " + fileName + " - error: " +  str(e))
            self.jsonMap['errormsg'] = str(e)
        else:
            self.jsonMap['userName'] = fileName
            self.jsonMap['safeFileName'] = safeFileName
            self.jsonMap['inputModes'] = self.session.getData(safeFileName).get('inputModes')

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