# (c) cavaliba.com - test_dashboard_compute_sections

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_NONE = {"perms": [], "is_admin": False, "username": "nobody"}
AAA_IMPORT = {"perms": ["p_data_import"], "is_admin": False, "username": "importer"}
AAA_IMPORT_EXPORT = {
    "perms": ["p_data_import", "p_data_export"], "is_admin": False, "username": "importexport",
}  # fmt: skip


class DashboardComputeSectionsTest(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_section_with_no_visible_cards_is_suppressed(self):
        self._set_content(
            """
            - section: "Tools"
              entries:
                - app: import
            """
        )
        sections = compute_dashboard(AAA_NONE)
        self.assertEqual(sections, [])

    def test_section_with_a_visible_card_shows_label_and_card(self):
        self._set_content(
            """
            - section: "Tools"
              entries:
                - app: import
            """
        )
        sections = compute_dashboard(AAA_IMPORT)
        self.assertEqual(len(sections), 1)
        self.assertEqual(sections[0]["label"], "Tools")
        self.assertEqual(sections[0]["cards"][0]["label"], "Import")

    def test_empty_dashboard_content_yields_no_sections(self):
        self._set_content("")
        sections = compute_dashboard(AAA_NONE)
        self.assertEqual(sections, [])

    def test_multiple_sections_preserve_order(self):
        self._set_content(
            """
            - section: "First"
              entries:
                - app: import
            - section: "Second"
              entries:
                - app: export
            """
        )
        sections = compute_dashboard(AAA_IMPORT_EXPORT)
        labels = [s["label"] for s in sections]
        self.assertEqual(labels, ["First", "Second"])

    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
            """
        )
        sections = compute_dashboard(AAA_IMPORT)
        labels = [c["label"] for c in sections[0]["cards"]]
        self.assertEqual(labels, ["Import"])
