from ..testing import PLONEINTRANET_ACTIVITYSTREAM_FUNCTIONAL_TESTING
from AccessControl import Unauthorized
from plone.app.testing import setRoles
from plone.app.testing import TEST_USER_ID
from plone.app.testing import TEST_USER_NAME
from plone.app.testing import TEST_USER_PASSWORD
from plone.testing.zope import Browser
from ploneintranet.microblog.interfaces import IMicroblogTool
from ploneintranet.microblog.statusupdate import StatusUpdate
from zope.component import queryUtility

import unittest


class TestStatusupdateTraverser(unittest.TestCase):

    layer = PLONEINTRANET_ACTIVITYSTREAM_FUNCTIONAL_TESTING

    def setUp(self):
        self.app = self.layer["app"]
        self.portal = self.layer["portal"]
        self.container = queryUtility(IMicroblogTool)

        # we need this before even adding a statusupdate
        setRoles(self.portal, TEST_USER_ID, ["Member"])

        self.su = StatusUpdate("foo bar")
        self.container.add(self.su)

        # Commit so that the test browser sees these changes
        import transaction

        transaction.commit()

        self.baseurl = "{}/statusupdate/{}/".format(
            self.portal.absolute_url(), self.su.id
        )
        self.browser = Browser(self.app)
        self.browser.handleErrors = False
        self.browser.addHeader(
            "Authorization", f"Basic {TEST_USER_NAME}:{TEST_USER_PASSWORD}"
        )

    def test_anon(self):
        browser = Browser(self.app)  # don't re-use self.browser
        url = self.baseurl + "post-menu.html"
        browser.open(url)
        # catches Unauthorized by redirecting to login form
        self.assertIn("__ac_password", browser.contents)

    def test_post_menu(self):
        url = self.baseurl + "post-menu.html"
        self.browser.open(url)
        self.assertTrue("panel-edit-post.html" in self.browser.contents)

    def test_nosuch_id(self):
        url = f"{self.portal.absolute_url()}/statusupdate/12345/post-menu.html"
        with self.assertRaises(KeyError):
            self.browser.open(url)

    def test_disallowed_view(self):
        url = self.baseurl + "absolute_url"
        with self.assertRaises(Unauthorized):
            self.browser.open(url)
