from AppKit import *
from Foundation import *
import objc
import PyObjCTools.AppHelper
import re
import traceback

WebMessageEditor = objc.lookUpClass('WebMessageEditor')
MVMailBundle = objc.lookUpClass('MVMailBundle')

ATTACH_EXP_STR = r'\battach(?:ment|ments|ing|ed)?\b'
ATTACH_EXP = re.compile(ATTACH_EXP_STR, re.I)

class MyWebMessageEditor(WebMessageEditor):
    __slots__ = ()
    def send_(self, sender):
        shouldSend = True
        try:
            attachments = self.attachments()
            if attachments is not None and len(attachments) > 0:
                # Message has attachment(s); no need to check.
                pass
            else:    
                message = self.backEnd().message()
                body = message.messageBody()
                data = unicode(body.rawData())
                for line in data.splitlines():
                    if line.lstrip().startswith('>'): continue # Ignore quoted replies                    
                    if ATTACH_EXP.search(line):
                        # Message claims to have an attachment, but we didn't find any!
                        shouldSend = False
                        self.showAttachmentAlertSheet()
                        break
        except Exception, e:
            NSLog("Trouble scanning outgoing message for attachments: %s: %s" % (e.__class__, e))
            traceback.print_exc()
        
        if shouldSend:
            super(MyWebMessageEditor, self).send_(sender)
    
    def showAttachmentAlertSheet(self):
        alert = NSAlert.alloc().init()
        alert.addButtonWithTitle_('Send')
        alert.addButtonWithTitle_('Cancel')
        alert.setMessageText_('Message Has No Attachment')
        alert.setInformativeText_("Your mail appears to refer to an attachment, "
                                  "but none exists.  Do you wish to continue?")
        alert.beginSheetModalForWindow_modalDelegate_didEndSelector_contextInfo_(
                    self.window(), self, self.attachmentAlertSheetDidEnd, 0)
                    
    def attachmentAlertSheetDidEnd(self, panel, returnCode, contextInfo):
        if returnCode == NSAlertFirstButtonReturn:
            super(MyWebMessageEditor, self).send_(contextInfo)
        else:
            NSLog('User canceled sending message without attachment.')
    attachmentAlertSheetDidEnd = PyObjCTools.AppHelper.endSheetMethod(attachmentAlertSheetDidEnd)
    
    
class MyPlugin(MVMailBundle):
    def initialize (cls):
        super(MyPlugin, cls).initialize()
        super(MyPlugin, cls).registerBundle()
        MyWebMessageEditor.poseAsClass_(WebMessageEditor)
        NSLog("MyPlugin registered with Mail")
    initialize = classmethod(initialize)