from plone.app.contenttypes.interfaces import ICollection
from plone.app.contenttypes.interfaces import IFolder
from ploneintranet.imagebank.interfaces import IImageBankCollection
from ploneintranet.imagebank.interfaces import IImageBankCollectionContainer
from ploneintranet.imagebank.interfaces import IImageBankFolder
from ploneintranet.userprofile.content.userprofile import IUserProfile
from Products.CMFPlone.interfaces.constrains import ISelectableConstrainTypes
from zope.component import adapter
from zope.interface import alsoProvides
from zope.lifecycleevent.interfaces import IObjectAddedEvent


@adapter(ICollection, IObjectAddedEvent)
def mark_collection_as_collection(obj, event):
    """If the object is a child of an IImageBankCollectionContainer,
    mark the object as a collection by adding the IImageBankCollection interface."""
    if not IImageBankCollectionContainer.providedBy(event.newParent):
        return

    alsoProvides(obj, IImageBankCollection)


@adapter(IFolder, IObjectAddedEvent)
def mark_folder_as_collection(obj, event):
    """If the object is a child of an IImageBankCollectionContainer,
    mark the object as a collection by adding the IImageBankCollection interface."""
    if not (
        IImageBankCollectionContainer.providedBy(event.newParent)
        or IUserProfile.providedBy(event.newParent)
    ):
        return

    if IImageBankCollectionContainer.providedBy(obj):
        # We should not mark the collection container itself.
        return

    alsoProvides(obj, IImageBankFolder)
    constraints = ISelectableConstrainTypes(obj)
    constraints.setConstrainTypesMode(1)
    constraints.setLocallyAllowedTypes(["Image"])
