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

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

import re
import traceback


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

HTML_QUOTE_STR = ur'<BLOCKQUOTE(?:\s|=)+type=3D"cite">.*?</BLOCKQUOTE>'
HTML_QUOTE_EXP = re.compile(HTML_QUOTE_STR, re.I|re.M|re.S)

class MyMessageEditor(MailDocumentEditor):
    __slots__ = ()

    def send_(self, sender):
        shouldSend = True
        try:
            attachments = self.backEnd().attachments()
            if attachments is not None and len(attachments) > 0:
                # Message has attachment(s); no need to check.
                pass
            else:
                message = self.backEnd().message()
                data = message.rawSource()
                data = HTML_QUOTE_EXP.sub(u'', data) # Ignore HTML quoted replies
                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("[ASP] Trouble scanning outgoing message for attachments: %s: %s" % (e.__class__, e))
            traceback.print_exc()
    
        if shouldSend:
            super(MyMessageEditor, 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(MyMessageEditor, self).send_(contextInfo)
        else:
            NSLog(u'[ASP] User canceled sending message without attachment.')
    attachmentAlertSheetDidEnd = PyObjCTools.AppHelper.endSheetMethod(attachmentAlertSheetDidEnd)
    
    
class MyPlugin(MVMailBundle):
    def initialize (cls):
        MVMailBundle.registerBundle()
        MyMessageEditor.poseAsClass_(MailDocumentEditor)
    initialize = classmethod(initialize)