from datetime import datetime
from plone import api
from plone.app.testing import login
from ploneintranet.userprofile.tests.base import BaseTestCase
from ploneintranet.userprofile.tests.test_sync import install_mock_pas_plugin
from ploneintranet.userprofile.tests.test_sync import TESTING_PLUGIN_ID
from ploneintranet.workspace.config import INTRANET_USERS_GROUP_ID
from Products.PlonePAS.events import UserLoggedInEvent
from zope import event


class TestLoginSubscribers(BaseTestCase):
    def setUp(self):
        super().setUp()
        self.login_as_portal_owner()
        install_mock_pas_plugin()

    def _create_and_login_member(self):
        """This method creates"""
        username = "adam"
        # Create a member
        member = api.user.create(email="test@test.com", username=username)
        # add in the external source some info about him
        acl_users = api.portal.get_tool(name="acl_users")
        plugin = acl_users[TESTING_PLUGIN_ID]
        plugin._storage[username] = {"email": "foo@bar.com"}
        # login the member
        login(self.portal, username)
        event.notify(UserLoggedInEvent(member))

    def test_new_user_membrane_indexed_on_login(self):
        brains = api.portal.get_tool("membrane_tool").searchResults(
            portal_type="ploneintranet.userprofile.userprofile"
        )
        self.assertEqual(len(brains), 0)
        self._create_and_login_member()
        brains = api.portal.get_tool("membrane_tool").searchResults(
            portal_type="ploneintranet.userprofile.userprofile"
        )
        self.assertEqual(len(brains), 1)
        obj = brains[0].getObject()
        self.assertEqual(obj.email, "foo@bar.com")
        self.assertIsInstance(obj.last_sync, datetime)

    def test_new_user_added_to_intranet_group(self):
        self._create_and_login_member()
        groups = api.group.get_groups(username="adam")
        self.assertIn(INTRANET_USERS_GROUP_ID, [x.id for x in groups])
