# (c) cavaliba.com - test_sidebar_compute_sections

from django.test import TestCase

import app_home.cache as cache
from app_home.configuration import set_configuration
from app_home.sidebar import compute_sidebar

AAA_NONE = {"perms": [], "is_admin": False, "username": "nobody"}
AAA_IMPORT = {"perms": ["p_data_import"], "is_admin": False, "username": "importer"}


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

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

    def test_section_with_no_visible_entries_is_suppressed(self):
        self._set_content(
            """
            - section: "Tools"
              entries:
                - app: import
            """
        )
        rows = compute_sidebar(AAA_NONE)
        self.assertEqual(rows, [])

    def test_section_with_a_visible_entry_shows_header_and_entry(self):
        self._set_content(
            """
            - section: "Tools"
              entries:
                - app: import
            """
        )
        rows = compute_sidebar(AAA_IMPORT)
        kinds = [(r["kind"], r["label"]) for r in rows]
        self.assertEqual(kinds, [("header", "Tools"), ("entry", "Import")])

    def test_top_level_entry_without_section_has_no_header(self):
        self._set_content(
            """
            - link: "/some/path/"
              label: "Standalone link"
            """
        )
        rows = compute_sidebar(AAA_NONE)
        self.assertEqual(rows, [{"kind": "entry", "label": "Standalone link", "icon": "fa-question", "url": "/some/path/"}])  # fmt: skip

    def test_empty_sidebar_content_yields_no_rows(self):
        self._set_content("")
        rows = compute_sidebar(AAA_NONE)
        self.assertEqual(rows, [])

    def test_mixed_visible_and_hidden_entries_in_same_section(self):
        self._set_content(
            """
            - section: "Mixed"
              entries:
                - app: import
                - link: "/no-perm/"
                  permission: p_never_granted
            """
        )
        rows = compute_sidebar(AAA_IMPORT)
        labels = [r["label"] for r in rows if r["kind"] == "entry"]
        self.assertEqual(labels, ["Import"])
