from logging import getLogger
from plone import api
from ploneintranet.notifications.sql import saconfig
from zope.interface.interfaces import ComponentLookupError

logger = getLogger(__name__)


def create_app():
    """Create the notifications app"""
    portal = api.portal.get()
    apps = portal.apps
    if "notifications" not in apps:
        api.content.create(
            container=apps,
            type="ploneintranet.layout.app",
            title="Notifications",
            id="notifications",
            safe_id=False,
            app="@@app-notifications",
            devices="desktop tablet mobile",
        )

    app = apps.notifications
    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_database():
    """Create the database tables if there is a database connection defined"""
    try:
        session = saconfig.session()
    except ComponentLookupError:
        logger.warning("No DB connection defined, skipping database creation")
        return
    saconfig.Base.metadata.create_all(session.bind.engine, checkfirst=True)


def post_default(context):
    """Actions needed after importing
    the ploneintranet.notifications:default profile
    """
    create_app()
    create_database()
