# (c) cavaliba.com - tests / sirene / archive

from django.test import TestCase, override_settings
from django.urls import reverse

import app_home.cache as cache
from tests import helper


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

        helper.add_admin_user(login="unittest")

        for i in range(1, 4):
            helper.add_instance(
                classname="sirene_message",
                keyname=f"msg0{i}",
                fields={
                    "is_enabled": "false",
                    "displayname": f"Incident {i}",
                    "category": "Incident",
                    "severity": "Major",
                    "content": "test content",
                },
            )

        helper.add_instance(
            classname="sirene_message",
            keyname="msg_other",
            fields={
                "is_enabled": "false",
                "displayname": "Maintenance window",
                "category": "Maintenance",
                "severity": "Minor",
                "content": "test content",
            },
        )

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_archive_no_filter_returns_all(self):
        response = self.client.get(reverse("app_sirene:archive"))
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["count"], 4)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_archive_single_keyword_filter(self):
        response = self.client.post(reverse("app_sirene:archive"), {"query": "incident"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["count"], 3)

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_archive_two_keywords_are_anded(self):
        response = self.client.post(reverse("app_sirene:archive"), {"query": "incident 2"})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["count"], 1)
        self.assertEqual(response.context["pages"][0]["displayname"], "Incident 2")

    @override_settings(CAVALIBA_AUTH_MODE="unittest")
    def test_archive_pagination_size_one(self):
        response = self.client.get(reverse("app_sirene:archive"), {"size": 1, "page": 1})
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context["count"], 4)
        self.assertEqual(len(response.context["pages"]), 1)
        self.assertEqual(response.context["page_last"], 5)
