from logging import getLogger
from plone import api

logger = getLogger()


def create_search_app():
    """Create the search application"""
    portal = api.portal.get()
    apps = portal.apps
    if "search" in apps and not apps.search.app:
        api.content.delete(obj=apps.search)
    if "search" not in apps:
        api.content.create(
            container=apps,
            type="ploneintranet.layout.app",
            title="Search",
            id="search",
            safe_id=False,
            app="@@search",
            devices="desktop tablet",
        )

    app = apps.search
    if api.content.get_state(app) == "published":
        return
    try:
        api.content.transition(app, to_state="published")
    except BaseException:
        logger.exception("Cannot publish the app: %r", app)


def post_default(context):
    """Actions needed after importing
    the ploneintranet.search:default profile
    """
    create_search_app()
