from plone import api
from plone.namedfile.file import NamedBlobFile
from ploneintranet.notifications.testing import IntegrationTestCase


class TestNotificationEmail(IntegrationTestCase):
    def setUp(self):
        super().setUp()
        self.portal = self.layer["portal"]
        self.request = self.layer["request"]

        self.mailhost = self.portal.MailHost

    def test_dummy_email(self):
        """Test, if emails are encoded correctly.
        HTML is for the plain text part in multipart messages stripped out,
        links are replaced with Text + URL Reference.
        """
        view = api.content.get_view("dummy-email", self.portal, self.request.clone())
        view.send_email()
        message_lines = self.mailhost.messages[0].decode().splitlines()
        self.assertIn("From: Plone site <noreply@example.com>", message_lines)
        self.assertIn("Reply-To: =?utf-8?q?foo=40example=2Ecom?=", message_lines)
        self.assertIn("To: bar@example.com", message_lines)
        self.assertIn("Subject: =?utf-8?q?Invoice_due?=", message_lines)
        self.assertIn("Refer to our terms and conditions [1]", message_lines)
        self.assertIn("Privacy policy [2]", message_lines)
        self.assertIn("[1] https://tools.ietf.org/html/rfc822", message_lines)
        self.assertIn("[2] https://tools.ietf.org/html/rfc2822", message_lines)

    def test_dummy_email_attachments(self):
        """"""
        with api.env.adopt_user("admin"):
            api.content.create(type="Folder", container=self.portal, id="test-folder")
            api.content.create(
                type="File",
                container=self.portal["test-folder"],
                id="test-file",
                file=NamedBlobFile(data=b"Attachment data", filename="dummy.txt"),
            )
            view = api.content.get_view(
                "dummy-email", self.portal["test-folder"], self.request.clone()
            )

            view.send_email()

        message_lines = self.mailhost.messages[0].decode().splitlines()
        self.assertIn("Please give us your home banking credentials", message_lines)
        self.assertIn(
            'Content-Disposition: attachment; filename="dummy.txt"', message_lines
        )
        self.assertIn("Attachment data", message_lines)
