from plone import api
from ploneintranet.layout.app import apps_container_id

_marker = object()


def _get_apps_view():
    apps_container = api.portal.get().get(apps_container_id)
    return api.content.get_view(name="apps.html", context=apps_container)


def get(app_id: str, default=_marker):
    """Get an app by its id.

    :param app_id: id of the app
    :type app_id: string
    :param default: Object that will be returned in case the app is not found
    :type default: object
    :raises KeyError: No app with the given id is found and no default was specified
    :raises NameError: The given id is not unique
    :returns: App object with the given id
    :rtype: `ploneintranet.layout.app.App` object
    """
    apps_view = _get_apps_view()
    try:
        return apps_view.get_app_by_id(app_id)
    except KeyError:
        if default is not _marker:
            return default
        raise


def get_apps() -> list:
    """List all apps in the site.

    :returns: List of apps
    :rtype: list of `ploneintranet.layout.app.App` objects
    """
    apps_view = _get_apps_view()
    return apps_view.all_apps()
