from plone import api
from ploneintranet.notifications.sql.saconfig import Notification
from ploneintranet.notifications.sql.saconfig import session
from zope.i18nmessageid import Message

import unittest


class NotificationTestCase(unittest.TestCase):
    def assertUserReceivesNotificationsOnChannels(
        self, user_id, channels, category=None
    ):
        """Check that the user has the right number of notifications"""
        notifications = session.query(Notification).filter_by(recipient_id=user_id)
        self.assertEqual(notifications.count(), len(channels))
        self.assertSetEqual(
            {notification.channel for notification in notifications},
            channels,
        )
        if category:
            self.assertSetEqual(
                {notification.category for notification in notifications},
                {category},
            )

    def assertInUserNotification(self, user_id, text):
        """Check that the user gets the right notification text"""
        notifications = session.query(Notification).filter_by(recipient_id=user_id)
        notification = notifications.first()

        self.assertTrue(len(notification.logged_event.category_provider.categories))
        category = notification.logged_event.category_provider.categories[0]
        observed = category.get_message_for(notification)
        if isinstance(observed, Message):
            observed = api.portal.translate(observed)
        self.assertIn(text, observed)
