from logging import getLogger
from plone import api
from ploneintranet.imagebank.interfaces import IImageBankApp
from ploneintranet.imagebank.interfaces import IImageBankCollectionContainer
from Products.CMFPlone.interfaces.constrains import ISelectableConstrainTypes
from zope.interface import alsoProvides

logger = getLogger(__name__)


def create_image_bank_app():
    """Create the Image bank application"""
    portal = api.portal.get()
    apps = portal.apps
    if "image-bank" not in apps:
        logger.info("Creating the Image bank app")
        app = api.content.create(
            container=apps,
            type="ploneintranet.layout.app",
            title="Image bank",
            id="image-bank",
            safe_id=False,
            app="@@app-image-bank",
            devices="desktop tablet mobile",
            conditon="nothing",  # TODO: remove me
        )
        alsoProvides(app, IImageBankApp)


def create_image_bank_collection_container():
    """Create the Image bank collection

    This is a special folder that is used to store the collections for the image bank.

    Collections can be Plone folders or collections.
    """
    portal = api.portal.get()
    if "image-bank-collections" in portal:
        return

    logger.info("Creating the Image bank collections folder")
    container = api.content.create(
        container=portal,
        type="Folder",
        title="Image bank collections",
        id="image-bank-collections",
        safe_id=False,
    )
    alsoProvides(container, IImageBankCollectionContainer)
    constraints = ISelectableConstrainTypes(container)
    constraints.setConstrainTypesMode(1)
    constraints.setLocallyAllowedTypes(["Folder", "Collection"])
    api.content.transition(obj=container, to_state="published")


def create_default_collections():
    """Create the default collections for the image bank"""
    portal = api.portal.get()
    container = portal["image-bank-collections"]

    if "all-the-images" in container:
        return
    logger.info("Creating the default collection: All the images")
    collection = api.content.create(
        container=container,
        type="Collection",
        title="All the images",
        description="This is the list of all the images you have access to. Use the search to find specific images.",  # noqa: E501
        query=[
            {
                "i": "portal_type",
                "o": "plone.app.querystring.operation.string.is",
                "v": "Image",
            }
        ],
        sort_on="created",
        sort_reversed=True,
        id="all-the-images",
        safe_id=False,
    )
    api.content.transition(obj=collection, to_state="published")


def post_default(context=None):
    """Actions needed after importing
    the ploneintranet.imagebank:default profile
    """
    create_image_bank_app()
    create_image_bank_collection_container()
    create_default_collections()
