from logging import getLogger
from plone import api
from ploneintranet.contacts.interfaces import IContactsContainer
from zope.interface import alsoProvides

logger = getLogger()


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

    app = apps.contacts
    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 create_contact_container(context=None):
    portal = api.portal.get()
    if "contacts" in portal:
        container = portal.contacts
    else:
        container = api.content.create(
            container=portal,
            type="Folder",
            id="contacts",
            title="Contacts",
        )
    alsoProvides(container, IContactsContainer)

    if api.content.get_state(container) != "published":
        logger.info("Publishing the contact container %s", container.getId())
        try:
            api.content.transition(container, "publish")
        except BaseException:
            logger.exception(
                "Cannot publish the contact container %s", container.getId()
            )
            try:
                api.content.transition(container, "publish_internally")
            except BaseException:
                logger.exception(
                    "Cannot publish the contact container %s internally",
                    container.getId(),
                )
    return container


def post_default(context):
    """Actions needed after importing
    the ploneintranet.calendar:default profile
    """
    create_contact_container()
    create_contacts_app()
