from collective.mustread.behaviors.maybe import IMaybeMustRead
from collective.mustread.behaviors.track import ITrackReadEnabled
from plone import api
from plone.app.testing import login
from plone.app.testing import TEST_USER_NAME
from plone.behavior.interfaces import IBehaviorAssignable
from ploneintranet.news.testing import IntegrationTestCase
from Products.CMFPlone.utils import get_installer

PROJECTNAME = "ploneintranet.news"


class InstallTestCase(IntegrationTestCase):
    """Test installation of this product into Plone."""

    def setUp(self):
        self.portal = self.layer["portal"]
        self.installer = get_installer(self.portal, self.layer["request"])
        login(self.portal, TEST_USER_NAME)

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

    def test_app_installed(self):
        self.assertIn("news", self.portal)

    def test_section_installed(self):
        self.assertTrue(len(self.portal.news.sections()) > 0)

    def test_mustread_installed(self):
        self.assertTrue(self.installer.is_product_installed("collective.mustread"))

    def test_mustread_behaviors_installed(self):
        item = api.content.create(
            type="News Item", title="foo", container=self.portal.news["company-news"]
        )
        assignable = IBehaviorAssignable(item)
        active = [x.interface for x in assignable.enumerateBehaviors()]
        self.assertTrue(IMaybeMustRead in active)
        self.assertTrue(ITrackReadEnabled in active)

    def test_frontpage_setup(self):
        app = self.portal.news
        self.assertEqual(app.grid, "sc")
        section = app["company-news"]
        self.assertDictEqual(
            app.columns["2"][section.UID()],
            {
                "num_items": 4,
                "show_title": False,
                "show_border": False,
                "grid": "1-3",
                "show_descriptions": True,
                "num_rows": "2",
            },
        )


class UninstallTestCase(IntegrationTestCase):
    """Test this product is properly uninstalled."""

    def setUp(self):
        self.portal = self.layer["portal"]
        self.installer = get_installer(self.portal, self.layer["request"])
        self.installer.uninstall_product(PROJECTNAME)

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

    def test_app_removed(self):
        self.assertNotIn("news", self.portal)

    # mustread is uninstalled from the suite uninstall handler
