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

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.utils.translation import override, ugettext

from pinax.notifications.backends.email import EmailBackend

from mtp.apps.themes.models import Theme


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
        ----------
        recipient: ``mtp.apps.accounts.models.MTPUser`` instance
            The user to send the email to
        sender: whatever
            This is just added to context, so you can use whatever you want.
        notice_type: ``pinax.notifications.models.NoticeType`` instance
            The pinax notification type object.
        extra_context: dict
            Key / values to feed the template with. Can also contain a special `attachments`
            key which is a list of valid ``django.core.mail.EmailMessage.attachments`` that will be
            used to attach files to the email.

        See Also
        --------
        - https://github.com/pinax/pinax-notifications
        - https://docs.djangoproject.com/fr/1.8/topics/email/#emailmessage-objects

        Notes
        -----
        We are using ``EmailMultiAlternatives.send`` instead of ``send_mail`` because we need
        attachments features. We use ``EmailMultiAlternatives`` instead of ``EmailMessage``
        because we need an HTML version of the email.

        """

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

        # Get and render the notification parts using the context.
        with override(recipient.natural_language):
            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 ``EmailMultiAlternatives.send``.
        msg = EmailMultiAlternatives(
            subject=subject,
            body=messages['body.txt'],
            from_email=settings.DEFAULT_FROM_EMAIL,
            to=[recipient.email],
            attachments=extra_context.get('attachments'),
        )
        msg.attach_alternative(messages['body.html'], 'text/html')
        msg.send()
