"""Communication model"""
from sqlalchemy import UniqueConstraint
from sqlalchemy.dialects.postgresql import ENUM

from ..database import db


# https://www.hl7.org/fhir/valueset-event-status.html
event_status_types = ENUM(
    'preparation', 'in-progress', 'suspended', 'aborted', 'completed',
    'entered-in-error', 'unknown', name='event_statuses',
    create_type=False)


class Communication(db.Model):
    """Model representing a FHIR-like Communication Resource

    Used to track communications tied to a user `basedOn` a
    CommunicationRequest.

    """
    __tablename__ = 'communications'
    id = db.Column(db.Integer, primary_key=True)
    status = db.Column('status', event_status_types, nullable=False)

    # FHIR Communication spec says `basedOn` can retur to any
    # object.  For current needs, this is always a CommunicationRequest
    communication_request_id = db.Column(
        db.ForeignKey('communication_requests.id'), nullable=False)
    communication_request = db.relationship('CommunicationRequest')

    user_id = db.Column(db.ForeignKey(
        'users.id', ondelete='cascade'), nullable=False)

    # message_id is null until sent
    message_id = db.Column(db.ForeignKey(
        'email_messages.id', ondelete='cascade'), nullable=True)

    __table_args__ = (
        UniqueConstraint(
            communication_request_id, user_id,
            name='_communication_request_user'),
    )

    def __str__(self):
        return (
            'Communication for {0.user_id}'
            ' of {0.communication_request_id}'.format(self))

@@ -118,27 +118,106 @@
 om .
-.database import db
+app_text import app_text, MailResource%0Afrom ..database import db%0Afrom .message import EmailMessage
 %0A%0A%0A#
@@ -1645,8 +1645,694 @@
 (self))%0A
+%0A    def app_text_key(self):%0A        return ('CommunicationRequest %7B0.name%7D %7B0.notify_days_after_event%7D'%0A                ''.format(self))%0A%0A    def generate_and_send(self):%0A        %22Collate message details and send%22%0A        args = %7B'first_name': self.user.first_name,%0A                'last_name': self.user.last_name%7D%0A%0A        mailresource = MailResource(%0A            app_text(self.app_text_key()),%0A            variables=args)%0A%0A        self.message = EmailMessage(%0A            subject=mailresource.subject,%0A            body=mailresource.body,%0A            recipients=self.user.email,%0A            user_id=self.user.id)%0A        self.message.send_message()%0A        self.status = 'completed'%0A

Add method to generate_and_send() queued communications