"""This module holds the email backend for the ``common`` app."""

from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.translation import ugettext

from pinax.notifications.backends.email import EmailBackend


class MultipartEmailBackend(EmailBackend):
    """The email backend to send multipart/alternative notifications."""

    def deliver(self, recipient, sender, notice_type, extra_context):
        """Format the notification with the context and send it using django
        ``send_mail`` method.

        Parameters
        ----------
        context : ``django.template.Context`` instance. 
            The context to use to render the notification.
        subject : str
            The subject of the notification.
        body : str
            The text body of the notification.
        html_body : str
            The html body of the notification.

        See Also
        --------
        https://github.com/pinax/pinax-notifications

        """

        # Get the default context and update it.
        context = self.default_context()
        context.update({
            'recipient': recipient,
            'sender': sender,
            'notice': ugettext(notice_type.display),
            'master_url': settings.MASTER_INSTANCE_URL
        })
        context.update(extra_context)

        # Get and render the notification parts using the context.
        messages = self.get_formatted_messages((
            'subject.txt',
            'body.txt',
            'body.html'
        ), notice_type.label, context)

        # Remove the newlines from the subject.
        subject = ''.join(messages['subject.txt'].splitlines())

        # Finally send the notification using django ``send_mail``.
        send_mail(
            subject=subject,
            message=messages['body.txt'],
            html_message=messages['body.html'],
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[recipient.email]
        )
