from bs4 import BeautifulSoup
from plone import api
from plone.app.testing import login
from plone.app.testing.interfaces import SITE_OWNER_NAME
from plone.app.textfield.value import RichTextValue
from ploneintranet.docconv.client.pdf import Converter
from ploneintranet.docconv.client.testing import IntegrationTestCase
from ploneintranet.docconv.client.utils import PDF_FILENAME
from ploneintranet.testing import dummy_image

import os


class TestHTMLToPDF(IntegrationTestCase):
    """Test views for ploneintranet.docconv.client"""

    def setUp(self):
        """Custom shared utility setup for tests."""
        self.portal = self.layer["portal"]
        login(self.portal.aq_parent, SITE_OWNER_NAME)
        self.document = api.content.create(self.portal, id="Doc1", type="Document")
        # XXX Increase the size of this one to have more meaningful scales
        self.image = api.content.create(
            container=self.portal,
            type="Image",
            id="image.png",
            image=dummy_image(filename="plone.jpg"),
        )

    def test_convert_virtual_url(self):
        converter = Converter(self.document)
        self.assertEqual(
            converter.convert_virtual_url("http://notplone/some.img"),
            "http://notplone/some.img",
        )
        self.assertEqual(
            converter.convert_virtual_url("http://nohost/plone/some.img"),
            "/plone/some.img",
        )
        self.document.REQUEST["VIRTUAL_URL_PARTS"] = (
            "http://quaive.com/",
            "quaive",
            "workspaces/w1/a-doc",
        )
        self.assertEqual(
            converter.convert_virtual_url("http://quaive.com/quaive/some.img"),
            "/plone/some.img",
        )
        # Support the case when the first element
        # of REQUEST['VIRTUAL_URL_PARTS'] does not end with a slash
        self.document.REQUEST["VIRTUAL_URL_PARTS"] = (
            "http://quaive.com",
            "quaive",
            "workspaces/w1/a-doc",
        )
        self.assertEqual(
            converter.convert_virtual_url("http://quaive.com/quaive/some.img"),
            "/plone/some.img",
        )

    def test_extract_images(self):
        converter = Converter(self.document)
        with converter.get_storage_dir() as storage_dir:
            converter.storage_dir = storage_dir
            tmpdir = os.path.join(converter.storage_dir, "images")
            os.mkdir(tmpdir)
            doc_html = '<body><img src="http://nohost/plone/image.png"/><body>'
            doc_soup = BeautifulSoup(doc_html, features="lxml")
            html = converter.extract_images(doc_soup, tmpdir)
            self.assertTrue(f'src="file://{tmpdir}/image0.png"' in str(html))
            self.assertTrue(os.path.exists(os.path.join(tmpdir, "image0.png")))

    def test_get_local_image(self):
        mini_target_bytes = 5131
        mini_target_size = (252, 57)
        converter = Converter(self.document)
        # Check if we are able to resolve an image
        local_image_path = "/".join(self.image.getPhysicalPath())
        observed = converter.get_local_image(local_image_path)
        self.assertEqual(len(observed[0]), 5131)
        self.assertTupleEqual(observed[1:], (252, 57))
        # even if it is scaled
        local_mini_path = local_image_path + "/@@images/image/mini"
        observed = converter.get_local_image(local_mini_path)
        # Image compression may return different results on different platforms
        self.assertAlmostEqual(len(observed[0]), mini_target_bytes, delta=10)
        self.assertTupleEqual(observed[1:], mini_target_size)
        # Test the URL you can find in documents that contain embedded images
        images = self.image.restrictedTraverse("images")
        scale = images.scale(fieldname="image", mode="thumbnail", height=45, width=200)
        scale_url = scale.absolute_url()
        scale_path = scale_url.partition("/plone/")[-1]
        observed = converter.get_local_image(scale_path)
        # Image compression may return different results on different platforms
        self.assertAlmostEqual(len(observed[0]), 2626, delta=10)
        self.assertTupleEqual(observed[1:], (200, 45))

    def test_run_conversion(self):
        raw_text = "¯\\_(ツ)_//¯<br/>"
        richtext = RichTextValue(
            raw=raw_text, mimeType="text/plain", outputMimeType="text/x-html-safe"
        )
        self.document.text = richtext
        converter = Converter(self.document)
        with converter.get_storage_dir() as storage_dir:
            converter.storage_dir = storage_dir
            converter.run_conversion()
            pdf_path = os.path.join(converter.storage_dir, PDF_FILENAME)
            self.assertTrue(os.path.exists(pdf_path))
