from plone import api
from ploneintranet import api as pi_api
from ploneintranet.core import _
from Products.Five.browser import BrowserView

import json


class BrowserIncomingMessage(BrowserView):
    @property
    def results(self):
        try:
            number = pi_api.messaging.get_inbox().new_messages_count
        except KeyError:
            # not even an inbox
            return []

        proto = api.content.get_view(
            "proto", context=self.context, request=self.request
        )
        lang = api.portal.get_current_language()
        title = api.portal.translate(
            _(
                "title_desktop_notification",
                default="Info from ${portal_title}.",
                mapping={"portal_title": proto.site_title},
            )
        )

        body = api.portal.translate(
            _(
                "title_chat_messages",
                default="You have ${number} incoming chat messages.",
                mapping={"number": number},
            )
        )
        url = f"{self.context.absolute_url()}/apps/messages"

        return [
            {
                "title": title,
                "lang": lang,
                "body": body,
                "icon": proto.logo_icon,
                "requireInteraction": True,
                "data": {
                    "url": url,
                },
            }
        ]

    def __call__(self):
        self.request.response.setHeader(
            "Content-Type", "application/json; charset=utf-8"
        )
        return json.dumps(self.results)
