import os, tempfile

from persistent import Persistent
from zope.interface import implements

from zope.app.container.contained import Contained
from zope.app.mail.mailer import SMTPMailer
from zope.app.mail.delivery import QueuedMailDelivery, QueueProcessorThread

from documentlibrary.core import interfaces

# XXX this whole module is rather icky. It's needed to override
# various classes in zope.app.mail to provide for TTW configurable
# mail. The whole zope.app.mail package is written with ZCML in mind.

QUEUE_PATH = os.path.join(tempfile.gettempdir(), 'documentlibrary-mail-queue')

# a local persistent version of SMTPMailer
class PersistentSMTPMailer(Persistent, Contained, SMTPMailer):
    implements(interfaces.IPersistentSMTPMailer)

# a local persistent version of QueuedMailDelivery
# queuePath is in the var directory
class PersistentQueuedMailDelivery(Persistent, Contained, QueuedMailDelivery):

    def __init__(self):
        # No need for queuePath argument to constructor.
        pass
    
    def _getQueuePath(self):
        return QUEUE_PATH
    
    queuePath = property(_getQueuePath)

def startQueueProcessor(mailer):
    thread = QueueProcessorThread()
    thread.setMailer(mailer)
    thread.setQueuePath(QUEUE_PATH)
    thread.start()
