from plone import api
from ploneintranet import api as pi_api
from zope.component import adapter
from zope.interface import Interface
from zope.publisher.interfaces.browser import IBrowserRequest
from zope.traversing.namespace import SimpleHandler


@adapter(Interface, IBrowserRequest)
class MicroblogPost(SimpleHandler):
    def traverse(self, name, ignored):
        """Get a microblog post"""
        post_id, comment_id = name.partition("-")[::2]
        status_update = pi_api.microblog.get_microblog()._get(int(post_id))
        if comment_id:
            return status_update.comments[int(comment_id)]

        # Set the proper acquisition chain so that permission can be checked properly
        pc = api.portal.get_tool("portal_catalog")
        parent_uid = status_update._microblog_context_uuid
        if parent_uid:
            for brain in pc.unrestrictedSearchResults(UID=parent_uid):
                parent = brain._unrestrictedGetObject()
                status_update.__of__(parent)
                break

        return status_update
