from AccessControl.unauthorized import Unauthorized
from ploneintranet import api as pi_api
from ploneintranet.notifications.sql import saconfig
from Products.Five import BrowserView


class NotificationView(BrowserView):
    """Used in email notifications and in the notification panel if the notification
    is not read yet.
    Register the read and redirect to the notification URL.
    """

    def mark_clicked(self):
        """Mark the notification as clicked if it is not already clicked and
        also mark the sibling "record notification" if the channel is not record
        """
        if self.context.clicked:
            return

        self.context.mark_clicked()

        if self.context.channel == "record":
            return

        Notification = saconfig.Notification
        session = saconfig.session()
        for record_notification in session.query(Notification).filter(
            Notification.channel == "record",
            Notification.logged_event_uid == self.context.logged_event_uid,
            Notification.recipient_id == self.context.recipient_id,
            Notification.clicked == None,  # noqa: E711
        ):
            # Mirror the clicked status to the record channel,
            # so we have an aggregated view of all clicked notifications
            # for that user across whichever channel they came in via.
            record_notification.mark_clicked()
            pi_api.push.notification_counter_changed_for(self.context.recipient_id)

    def __call__(self):
        user = pi_api.userprofile.get_current()
        if not user:
            raise Unauthorized

        if self.context.recipient_id == user.getId():
            self.mark_clicked()

        # Rely on the security of the URL we are going to hit next
        return self.request.response.redirect(self.context.context_absolute_url())
