from Acquisition import aq_chain
from Acquisition import aq_inner
from plone.base.utils import pretty_title_or_id
from ploneintranet.layout.app import IApp
from ploneintranet.layout.interfaces import IApplicationLabel
from Products.CMFPlone.browser.interfaces import INavigationBreadcrumbs
from Products.Five import BrowserView
from zope.interface import implementer


@implementer(INavigationBreadcrumbs)
class OneLevelBreadcrumbs(BrowserView):
    def breadcrumbs(self):
        context = aq_inner(self.context)
        chain = aq_chain(context)
        chain = (elem for elem in chain if IApplicationLabel.providedBy(elem))
        label_item = next(chain, context)
        title = None
        if IApp.providedBy(label_item):
            title = getattr(self.context.app_view(self.request), "title", None)
        if not title:
            title = pretty_title_or_id(label_item, label_item)
        crumbs = (
            {
                "absolute_url": label_item.absolute_url(),
                "Title": title,
            },
        )
        return crumbs
