#! /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.                                   #
#                                                           #
#############################################################
from time import strftime

import mb_cgi
import Mobyle.Net
import Mobyle.MobyleError
from Mobyle.Registry import registry
from Mobyle.JobFacade import JobFacade

def process( self ):
    try:
        self.jsonMap['ok'] = str(False)
        message = self.request.getfirst('helpMessage',None)
        if(message is None):
            raise Mobyle.MobyleError.UserValueError(msg='please provide a request message.')
        userAddress = Mobyle.Net.EmailAddress( self.request.getfirst('helpEmail',None) )            
        jobId = self.request.getfirst('id',None)
        if jobId:
            jobServer = registry.getServerByJobId(self.request.getfirst('id',None))
        else:
            jobServer = registry.serversByName['local']
        if self.cfg.mailHelp()!=jobServer.help:
            helpAddress = Mobyle.Net.EmailAddress([jobServer.help, str(self.cfg.mailHelp())])
        else:
            helpAddress = Mobyle.Net.EmailAddress(self.cfg.mailHelp())
        helpEmail = Mobyle.Net.Email(helpAddress)
        msgDict = {
                     'USER': userAddress,
                     'SENDER': self.cfg.sender(),
                     'MSG': message,
                     'SESSION_ID': self.sessionKey,
                     'SESSION_EMAIL': self.session.getEmail(),
                     'SESSION_ACTIVATED': self.session.isActivated(),
                     'SESSION_AUTHENTICATED': self.session.isAuthenticated(),
                     'JOB_URL': jobId,
                     'JOB_DATE': strftime("%a, %d %b %Y %H:%M:%S +0000"),
                     'JOB_STATUS': JobFacade.getFromJobId(jobId).getStatus(),
                     'JOB_ERROR_PARAM': self.request.getfirst('errorparam',None),   
                     'JOB_ERROR_MSG': self.request.getfirst('errormsg',None),
                     'HELP': str(helpAddress)
                  } 
        helpEmail.send('HELP_REQUEST' , msgDict)
        receiptEmail = Mobyle.Net.Email( userAddress )
        receiptEmail.send('HELP_REQUEST_RECEIPT' , msgDict)
        self.jsonMap['ok'] = str(True)
        self.jsonMap['msg'] = helpEmail.getBody()
    except Mobyle.MobyleError.UserValueError, ue:
        self.jsonMap['errormsg'] = ue.message
        return
    except Mobyle.MobyleError.EmailError:
        self.jsonMap['errormsg'] = "please provide a valid email adress"
        return
        
if __name__ == "__main__":
    mb_cgi.JSONCGI(processFunction=process,useSession=True)