# (c) cavaliba.com - test_dashboard_link_permission

from django.test import TestCase

import app_home.cache as cache
from app_home.configuration import set_configuration
from app_home.dashboard import compute_dashboard

AAA_GRANTED = {"perms": ["p_this_link_allowed"], "is_admin": False, "username": "granted"}
AAA_NONE = {"perms": [], "is_admin": False, "username": "nobody"}


class DashboardLinkPermissionTest(TestCase):
    def setUp(self):
        cache.clear()

    def _set_content(self, yaml_text):
        set_configuration(
            appname="home", keyname="DASHBOARD_CONTENT", value=yaml_text, description="",
            page="", order=100,
        )  # fmt: skip
        cache.clear()

    def test_link_without_permission_is_always_visible(self):
        self._set_content(
            '- section: Ext\n  entries:\n    - link: "/path/to/a/link"\n      label: "my label"\n'
        )
        sections = compute_dashboard(AAA_NONE)
        card = sections[0]["cards"][0]
        self.assertEqual(card["url"], "/path/to/a/link")
        self.assertEqual(card["label"], "my label")
        self.assertEqual(card["kind"], "link")
        self.assertNotIn("count", card)

    def test_link_with_permission_hidden_when_not_granted(self):
        self._set_content(
            '- section: Ext\n  entries:\n    - link: "/path/to/a/link"\n      permission: p_this_link_allowed\n'
        )
        sections = compute_dashboard(AAA_NONE)
        self.assertEqual(sections, [])

    def test_link_with_permission_visible_when_granted(self):
        self._set_content(
            '- section: Ext\n  entries:\n    - link: "/path/to/a/link"\n      permission: p_this_link_allowed\n'
        )
        sections = compute_dashboard(AAA_GRANTED)
        self.assertEqual(len(sections[0]["cards"]), 1)

    def test_link_label_defaults_to_url(self):
        self._set_content('- section: Ext\n  entries:\n    - link: "/no-label-here/"\n')
        sections = compute_dashboard(AAA_NONE)
        self.assertEqual(sections[0]["cards"][0]["label"], "/no-label-here/")
