from plone import api
from plone.browserlayer.utils import registered_layers
from ploneintranet.search.testing import IntegrationTestCase
from Products.CMFPlone.utils import get_installer

PROJECTNAME = "ploneintranet.search"


class TestInstall(IntegrationTestCase):
    def setUp(self):
        super().setUp()
        self.portal = self.layer["portal"]
        self.installer = get_installer(self.portal, self.layer["request"])

    def test_product_is_installed(self):
        self.assertTrue(self.installer.is_product_installed(PROJECTNAME))

    def test_addon_layer(self):
        layers = [layer.getName() for layer in registered_layers()]
        self.assertIn("IPloneintranetSearchLayer", layers)

    def test_index_installed(self):
        catalog = api.portal.get_tool("portal_catalog")
        self.assertIn("friendly_type_name", catalog.indexes())
        self.assertIn("friendly_type_name", catalog.schema())


class TestUninstall(IntegrationTestCase):
    def setUp(self):
        super().setUp()
        self.portal = self.layer["portal"]
        self.installer = get_installer(self.portal, self.layer["request"])
        with api.env.adopt_roles(["Manager"]):
            self.installer.uninstall_product(PROJECTNAME)

    def test_uninstalled(self):
        self.assertFalse(self.installer.is_product_installed(PROJECTNAME))

    def test_addon_layer_removed(self):
        layers = [layer.getName() for layer in registered_layers()]
        self.assertNotIn("IPloneintranetSearchLayer", layers)

    def test_index_removed(self):
        catalog = api.portal.get_tool("portal_catalog")
        self.assertNotIn("friendly_type_name", catalog.indexes())
        self.assertNotIn("friendly_type_name", catalog.schema())
