from collective.ftw.upgrade import UpgradeStep
from dataclasses import dataclass
from plone import api
from plone.app.contenttypes.interfaces import ICollection
from plone.app.contenttypes.interfaces import IFolder
from ploneintranet.imagebank.interfaces import IImageBankCollectionContainer
from ploneintranet.imagebank.subscribers.on_added import mark_collection_as_collection
from ploneintranet.imagebank.subscribers.on_added import mark_folder_as_collection


@dataclass
class DummyEvent:
    newParent: object


class MarkTheImageBankCollections(UpgradeStep):
    """Mark the image bank collections."""

    def __call__(self):
        self.install_upgrade_profile()
        brains = api.content.find(object_provides=IImageBankCollectionContainer)
        containers = [brain.getObject() for brain in brains]

        for container in containers:
            event = DummyEvent(newParent=container)

            brains = api.content.find(context=container, object_provides=ICollection)
            for brain in brains:
                obj = brain.getObject()
                mark_collection_as_collection(obj, event)
                obj.reindexObject(idxs=["object_provides"])

            brains = api.content.find(context=container, object_provides=IFolder)
            for brain in brains:
                obj = brain.getObject()
                mark_folder_as_collection(obj, event)
                obj.reindexObject(idxs=["object_provides"])
