"""Model classes for message data"""
from datetime import datetime
from textwrap import fill
from flask import current_app
from flask_mail import Message
from flask_mail import email_dispatched

from ..database import db
from ..extensions import mail


def log_message(message, app):
    """Configured to handle signals on email_dispatched - log the event"""
    app.logger.info(u"Message sent; To: {0} Subj: {1}".\
            format(message.recipients, message.subject))


email_dispatched.connect(log_message)


class EmailMessage(db.Model):
    __tablename__ = 'email_messages'
    id = db.Column(db.Integer, primary_key=True)
    subject = db.Column(db.String(255), nullable=False)
    recipients = db.Column(db.Text, nullable=False)
    sender = db.Column(db.String(255), nullable=False)
    sent_at = db.Column(db.DateTime, default=datetime.utcnow)
    body = db.Column(db.Text, nullable=False)
    # nullable as anonymous support requests won't have associated users
    user_id = db.Column(db.Integer(), db.ForeignKey('users.id',
        ondelete='CASCADE'))

    def send_message(self):
        message = Message(subject=self.subject,
                sender=current_app.config['DEFAULT_MAIL_SENDER'],
                recipients=self.recipients.split())
        message.html = fill(self.body, width=280)
        mail.send(message)

    def __str__(self):
        return "EmailMessage subj:{} sent_at:{}".format(self.subject,
                                                        self.sent_at)

@@ -188,16 +188,52 @@
 atched%0A%0A
+from ..audit import auditable_event%0A
 from ..d
@@ -280,16 +280,39 @@
 rt mail%0A
+from .user import User%0A
 %0A%0Adef lo
@@ -1393,16 +1393,606 @@
 ssage)%0A%0A
+        user = User.query.filter_by(email=self.sender).first()%0A        user_id = user.id if user else self.user_id%0A        recipient = self.recipients.split()%5B0%5D%0A        subject = User.query.filter_by(email=recipient).first()%0A        subject_id = subject.id if subject else self.user_id%0A%0A        if user_id and subject_id:%0A            audit_msg = (%22EmailMessage '%7B0.subject%7D' sent to %22%0A                         %22%7B0.recipients%7D from %7B0.sender%7D%22.format(self))%0A            auditable_event(message=audit_msg, user_id=user_id,%0A                            subject_id=subject_id, context=%22user%22)%0A%0A
     def 

create audit after email message generation