from plone import api
from plone.namedfile import NamedBlobFile
from ploneintranet.search import testing
from Products.CMFCore.indexing import processQueue
from Products.CMFCore.interfaces import IIndexableObject
from zope.component import queryMultiAdapter

# https://stackoverflow.com/questions/17279712/what-is-the-smallest-possible-valid-pdf
PDF_DATA = """%PDF-1.0
1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 3 3]>>endobj
xref
0 4
0000000000 65535 f
0000000010 00000 n
0000000053 00000 n
0000000102 00000 n
trailer<</Size 4/Root 1 0 R>>
startxref
149
%EOF"""  # noqa: E501


class TestFriendlyName(testing.IntegrationTestCase):
    """Test the friendly type name generator."""

    def _create_content(self, **kw):
        obj = api.content.create(**kw)
        obj.reindexObject()
        return obj

    def setUp(self):
        super().setUp()
        self.portal = api.portal.get()
        self.catalog = api.portal.get_tool(name="portal_catalog")
        self.doc1 = self._create_content(
            type="Document", title="Test Doc", container=self.portal
        )
        self.file1 = self._create_content(
            type="File",
            title="Test PDF",
            container=self.portal,
            file=NamedBlobFile(
                data=PDF_DATA,
                filename="test-file.pdf",
                contentType="application/pdf",
            ),
        )
        self.file2 = self._create_content(
            type="File",
            title="Test Octet stream",
            container=self.portal,
            file=NamedBlobFile(
                data="blah blah",
                filename="test-file.so",
                contentType="application/octet-stream",
            ),
        )
        processQueue()

    def test_default_type(self):
        iobj = queryMultiAdapter((self.doc1, self.catalog), IIndexableObject)
        self.assertEqual(iobj.friendly_type_name, "Page")

        iobj = queryMultiAdapter((self.file1, self.catalog), IIndexableObject)
        self.assertEqual(iobj.friendly_type_name, "PDF document")

        # Check that we have really friendly names
        iobj = queryMultiAdapter((self.file2, self.catalog), IIndexableObject)
        self.assertEqual(iobj.friendly_type_name, "File")
