from plone import api
from ploneintranet import api as pi_api
from ploneintranet.imagebank.browser.app import ImageBankAppView
from ploneintranet.imagebank.browser.base import CollectionContainerListingView
from ploneintranet.imagebank.browser.panel import PanelCreateCollectionView
from ploneintranet.imagebank.interfaces import IImageBankFolder
from ploneintranet.imagebank.testing import PLONEINTRANET_IMAGEBANK_INTEGRATION_TESTING

import unittest


class TestImageBankApp(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"]
        self.collections_container = self.portal["image-bank-collections"]

    def get_view(self, form=None) -> ImageBankAppView:
        if form is not None:
            self.request.form.update(form)
        view: ImageBankAppView = api.content.get_view(
            "app-image-bank", self.app, self.request
        )
        return view

    def test_app_view_collection_container(self):
        view = self.get_view()
        self.assertEqual(view.collections_container, self.collections_container)

    def test_app_view_query(self):
        view = self.get_view()
        self.assertDictEqual(
            view.base_query,
            {
                "context": view.collections_container,
                "depth": 1,
                "portal_type": ["Collection", "Folder"],
                "sort_on": "sortable_title",
            },
        )
        self.assertDictEqual(
            view.query,
            {
                "context": view.collections_container,
                "depth": 1,
                "portal_type": ["Collection", "Folder"],
                "sort_on": "sortable_title",
            },
        )

    def test_app_view_query_with_searchable_text(self):
        view = self.get_view({"SearchableText": "foo"})
        self.assertDictEqual(
            view.base_query,
            {
                "context": view.collections_container,
                "depth": 1,
                "portal_type": ["Collection", "Folder"],
                "sort_on": "sortable_title",
            },
        )

        self.assertDictEqual(
            view.query,
            {
                "context": view.collections_container,
                "depth": 1,
                "portal_type": ["Collection", "Folder"],
                "SearchableText": "foo*",
                "sort_on": "sortable_title",
            },
        )

    def test_default_collection_displayed_in_the_app(self):
        view = self.get_view()
        self.assertListEqual(
            [brain.getId for brain in view.batch],
            ["all-the-images"],
        )

    def test_collection_container_redirects_to_the_app(self):
        view = api.content.get_view(
            "listing_view", self.portal["image-bank-collections"], self.request
        )
        self.assertIsInstance(view, CollectionContainerListingView)
        self.assertEqual(view(), self.app.app_url())

    def test_panel_create_collection_on_container(self):
        view: PanelCreateCollectionView = api.content.get_view(
            "panel-create-collection", self.collections_container, self.request
        )
        with api.env.adopt_user("admin"):
            view.do_create(
                {
                    "title": "My Collection",
                    "visibility": ["intranet"],
                }
            )
        self.assertIn("my-collection", self.collections_container)

        collection = self.collections_container["my-collection"]
        self.assertEqual(collection.Title(), "My Collection")
        self.assertEqual(collection.Description(), "")
        with self.assertRaises(AttributeError):
            collection.visibility

        self.assertDictEqual(
            dict(collection.get_local_roles()),
            {"admin": ("Owner",), "intranet": ("Reader",)},
        )

        self.assertTrue(IImageBankFolder.providedBy(collection))

        with api.env.adopt_user("admin"):
            self.assertSetEqual(
                {fti.getId() for fti in collection.allowedContentTypes()}, {"Image"}
            )

        self.assertSetEqual(
            {fti.getId() for fti in collection.allowedContentTypes()}, set()
        )

    def test_panel_create_collection_on_userprofile(self):
        member = api.user.get_current()
        with api.env.adopt_user("admin"):
            userprofile = pi_api.userprofile.create(
                username=member.getId(),
                email=member.getProperty("email"),
                approve=True,
            )

        view: PanelCreateCollectionView = api.content.get_view(
            "panel-create-collection", userprofile, self.request
        )
        view.do_create({"title": "My Collection"})
        self.assertIn("my-collection", userprofile)

        collection = userprofile["my-collection"]

        self.assertEqual(collection.Title(), "My Collection")
        self.assertEqual(collection.Description(), "")
        with self.assertRaises(AttributeError):
            collection.visibility

        self.assertDictEqual(
            dict(collection.get_local_roles()), {member.getUserId(): ("Owner",)}
        )

        self.assertTrue(IImageBankFolder.providedBy(collection))
        self.assertSetEqual(
            {fti.getId() for fti in collection.allowedContentTypes()}, {"Image"}
        )
