"""This module holds the tests backend for the ``apps.common.notifications`` module."""

from django.conf import settings
from django.core import mail
from django.utils import translation

from pinax.notifications.models import NoticeType

from mtp.apps.common.notifications.backends.email import MultipartEmailBackend
from mtp.apps.common.tests.test_cases import MTPTestCase


class MultipartEmailBackendTestcase(MTPTestCase):
    """Test case for ``MultipartEmailBackend``"""

    @classmethod
    def setUpTestData(cls):
        """Create the notice type to user"""

        super().setUpTestData()

        cls.notice_type = NoticeType.objects.create(
            label='test',
            display='Title',
            description='Description',
            default=1
        )

        cls.backend = MultipartEmailBackend('email')

    def test_email_goes_out_ok(self):
        """Test we can send an email with this class"""

        # attach a file to the email
        context = {
            'attachments': [('file.txt', 'content', 'text/plain')]
        }

        self.backend.deliver(
            self.trainee,
            None,
            self.notice_type,
            context
        )

        # one mail has been sent
        self.assertEqual(len(mail.outbox), 1)
        sent_mail = mail.outbox[0]

        # attachment is set
        self.assertEqual(
            sent_mail.attachments,
            context['attachments']
        )

    def test_email_is_correctly_translated(self):
        """Test that the email content is correctly translated to the user's locale"""

        # Change the locale of the trainee to "fr"
        self.trainee.natural_language = settings.LANGUAGES[0][0]
        self.trainee.save()

        self.assertEqual(self.trainee.natural_language, 'fr')

        self.backend.deliver(
            self.trainee,
            None,
            self.notice_type,
            {}
        )

        # The content of the test email should be translated
        sent_mail = mail.outbox[0]

        with translation.override('fr'):
            translated_string = translation.ugettext('Password')

        self.assertIn(translated_string, sent_mail.subject)
        self.assertIn(translated_string, sent_mail.body)
        self.assertIn(translated_string, sent_mail.alternatives[0][0])
