from plone import api
from ploneintranet.imagebank.browser.app import ImageBankAppView
from ploneintranet.imagebank.interfaces import IImageBankCollection
from ploneintranet.imagebank.interfaces import IImageBankCollectionContainer
from ploneintranet.imagebank.testing import PLONEINTRANET_IMAGEBANK_INTEGRATION_TESTING

import unittest


class TestImageBankSetup(unittest.TestCase):

    layer = PLONEINTRANET_IMAGEBANK_INTEGRATION_TESTING

    def setUp(self):
        self.portal = self.layer["portal"]
        self.request = self.layer["request"]
        self.app = self.portal.apps["image-bank"]

    def test_app_created(self):
        self.assertIn("image-bank", self.portal.apps)

    def test_app_view_registered(self):
        view: ImageBankAppView = api.content.get_view(
            "app-image-bank", self.app, self.request
        )
        self.assertIsInstance(view, ImageBankAppView)

    def test_collection_container_created(self):
        self.assertIn("image-bank-collections", self.portal)
        container = self.portal["image-bank-collections"]
        with api.env.adopt_roles(["Contributor"]):
            self.assertSetEqual(
                {fti.getId() for fti in container.allowedContentTypes()},
                {"Collection", "Folder"},
            )
        self.assertEqual(api.content.get_state(container), "published")
        self.assertTrue(IImageBankCollectionContainer.providedBy(container))

    def test_default_collection_created(self):
        container = self.portal["image-bank-collections"]
        self.assertIn("all-the-images", container)
        collection = container["all-the-images"]
        self.assertEqual(collection.Title(), "All the images")
        self.assertEqual(api.content.get_state(collection), "published")
        self.assertTrue(IImageBankCollection.providedBy(collection))

    def test_collection_behaviors(self):
        portal_types = api.portal.get_tool("portal_types")
        fti = portal_types["Collection"]
        self.assertIn("plone.leadimage", fti.behaviors)

    def test_private_collections_addable(self):
        portal_types = api.portal.get_tool("portal_types")
        fti = portal_types["ploneintranet.userprofile.userprofile"]
        self.assertIn("Folder", fti.allowed_content_types)
