import appconfig as config
import logging
from google.appengine.api import mail
from google.appengine.api.mail import InvalidSenderError
from orangescape.model.engine.execution.ProcessEngine import ProcessNode
from orangescape.model.engine.exception.Error import CustomCommandError
from orangescape.model.engine.exception.ErrorMessage import Action1002, Action1003
from orangescape.model.server.util.metadatautil import getRootBranch

class MailProcessNode(ProcessNode):

    def enter(self):

        referenceCell = self.args.get('Reference-Cell')

        attachmentList = []
        if referenceCell and referenceCell.getSheetMetadata().getPublicCellMetadataDict().has_key('Attachment'):
            for attachmentInstance in self.session.getList(self.sheet, referenceCell):
                attachment = self.component.getAttachmentWithId(attachmentInstance)
                if attachment[0] is not None and attachment[1] is not None:
                    attachmentList.append(attachment)
                else:
                    logging.warn('Mail command: the child model %s(%s) of %s does not contain any attachment to send mail attachment'%(referenceCell.getSheetMetadata().getSheetName(), attachmentInstance.getSheetName(), self.sheet.getValue('SheetMetadataName')))

        self.sendMail(attachmentList)

    def sendMail(self, attachments):

        mailTo = self.args.get('To')
        mailSub = self.args.get('Subject')
        mailCC = self.args.get('CC')
        mailBCC = self.args.get('BCC')
        mailBody = self.args.get('Body')

        logging.info('Sending mail to %s Sub :%s'%(mailTo, mailSub))
        message = mail.EmailMessage(sender=config.EMAILID,subject=mailSub)
        if mailTo is None:
            raise CustomCommandError, Action1002 %(getRootBranch(self.activityDefinition.getBranch()),self.sheet.getSheetMetadata().getSheetName(), self.sheet.getSheetId())
        elif not mail.is_email_valid(mailTo):
            raise CustomCommandError, Action1003 %(mailTo,getRootBranch(self.activityDefinition.getBranch()),self.sheet.getSheetMetadata().getSheetName(), self.sheet.getSheetId())
        else:
            message.to = mailTo
            message.html = mailBody
            if mailCC is not None:
                message.cc = mailCC
            if mailBCC is not None:
                message.bcc = mailBCC
            if attachments:
                message.attachments = attachments
            try:
                message.send()
            except InvalidSenderError:
                raise CustomCommandError, "Unauthorized sender <B>%s</B>" %(self.args.get('From'))