# For guessing MIME type based on file name extension
from mimetypes import guess_type
from optparse import OptionParser
from orangescape.model.engine.execution.ProcessEngine import ProcessNode
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP
from com.orangescape.logging import PersistenceLogger
logger = PersistenceLogger.getLogger()
import logging
import appconfig as config

class MailProcessNode(ProcessNode):

        def enter(self):
            msg = MIMEMultipart('alternative')
            msg['From'] = self.args.get('From')
            msg['Subject'] = self.args.get('Subject')
            msg['To'] = self.args.get('To')
            msg['CC'] = self.args.get('CC')
            msg['BCC'] = self.args.get('BCC')
            msg['Body'] = self.args.get('Body')
            toList = []
            if msg['To']:
                toList.extend([mailId.strip() for mailId in self.args.get('To').split(",")])
            if msg['CC']:
                toList.extend([mailId.strip() for mailId in self.args.get('CC').split(",")])
            if msg['BCC']:
                toList.extend([mailId.strip() for mailId in self.args.get('BCC').split(",")])
            logging.info(toList)
            self.attachFiles(msg)
            """ Finally include body of mail message """
            msg.attach(MIMEText(msg['Body'], 'html'))
            mail_server = SMTP(config.EMAIL_SMTP_IP, config.EMAIL_SMTP_PORT)
            mail_server.ehlo()
            mail_server.starttls()
            mail_server.ehlo()
            mail_server.login(config.EMAIL_ADMIN_ID, config.EMAIL_ADMIN_PASSWORD)
            mail_server.sendmail(msg['From'], toList, msg.as_string())
            mail_server.quit()

        def attachFiles(self,msg):
            referenceCell = self.args.get('Reference-Cell')
            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:
                        fileName = attachment[0] or 'untitled.txt'
                        content = attachment[1]
                        ctype, encoding = guess_type(fileName)
                        if ctype is None or encoding is not None:
                            ctype = 'application/octet-stream'
                        maintype, subtype = ctype.split('/', 1)
                        logging.info('attaching file type %s'%(maintype))
                        if maintype == 'text':
                            fileattach = MIMEText(content, _subtype=subtype)
                        elif maintype == 'image':
                            fileattach = MIMEImage(content, _subtype=subtype)
                        elif maintype == 'audio':
                            fileattach = MIMEAudio(content, _subtype=subtype)
                        else:
                            fileattach = MIMEBase(maintype, subtype)
                            fileattach.set_payload(content)
                            encoders.encode_base64(fileattach)
                        fileattach.add_header('Content-Disposition', 'attachment', filename=fileName)
                        msg.attach(fileattach)
                    else:
                        logging.warn('Mail command: the child model %s of %s does not contain any attachment to send mail attachment'%(referenceCell.getSheetMetadata().getSheetName(), self.sheet.getValue('SheetMetadataName')))

