from plone.app.testing import login
from plone.i18n.interfaces import ILanguageSchema
from plone.registry.interfaces import IRegistry
from ploneintranet import api as pi_api
from ploneintranet.layout.testing import IntegrationTestCase
from ploneintranet.userprofile.testing import (
    PLONEINTRANET_USERPROFILE_INTEGRATION_TESTING,
)
from Products.PlonePAS.events import UserLoggedInEvent
from zope.component import getUtility
from zope.event import notify


class TestLanguageSettings(IntegrationTestCase):

    layer = PLONEINTRANET_USERPROFILE_INTEGRATION_TESTING

    def setUp(self):
        self.app = self.layer["app"]
        self.portal = self.layer["portal"]
        self.request = self.layer["request"]
        self.user = pi_api.userprofile.create(username="user")
        self.settings = getUtility(IRegistry).forInterface(
            ILanguageSchema, prefix="plone"
        )
        self.settings.available_languages = ["nl", "de"]
        self.settings.default_language = "nl"

    def test_language_set_on_login(self):
        self.user.setLanguage("de")
        login(self.portal, "user")
        notify(UserLoggedInEvent(self.user))
        self.assertEqual(self.request.response.cookies["I18N_LANGUAGE"]["value"], "de")

    def test_preferred_content_language_set_on_login(self):
        self.user.preferred_content_language = "de"
        login(self.portal, "user")
        notify(UserLoggedInEvent(self.user))
        self.assertEqual(self.request.response.cookies["I18N_LANGUAGE"]["value"], "de")
