"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: ksp-servicestelle@sgdnord.rlp.de
Created on: 24.08.23

"""
from django.urls import reverse
from django.utils.timezone import now

from ema.models import Ema, EmaDocument
from ema.settings import EMA_IDENTIFIER_TEMPLATE
from konova.tests.test_views import BaseTestCase
from konova.utils.message_templates import DOCUMENT_REMOVED_TEMPLATE
from user.models import UserAction


class EmaModelTestCase(BaseTestCase):
    def setUp(self) -> None:
        super().setUp()

    def test_str(self):
        self.assertEqual(str(self.ema), f"{self.ema.identifier}")

    def test_save(self):
        new_ema = Ema(
            title="Test"
        )
        self.assertIsNone(new_ema.identifier)

        new_ema.save()
        new_ema.refresh_from_db()

        self.assertIsNotNone(new_ema.identifier)
        self.assertIn("EMA-", new_ema.identifier)

    def test_is_ready_for_publish(self):
        self.assertIsNone(self.ema.recorded)
        self.assertFalse(self.ema.is_ready_for_publish())

        self.ema.set_recorded(self.superuser)
        self.ema.refresh_from_db()
        self.assertIsNotNone(self.ema.recorded)
        self.assertTrue(self.ema.is_ready_for_publish())

    def test_get_share_link(self):
        self.assertEqual(
            self.ema.get_share_link(),
            reverse("ema:share-token", args=(self.ema.id, self.ema.access_token))
        )

    def test_get_documents(self):
        self.assertEqual(self.ema.get_documents().count(), 0)

        doc = EmaDocument(
            instance=self.ema,
            date_of_creation=now().date(),
            comment="Test",
        )
        doc.save()
        docs = self.ema.get_documents()
        self.assertEqual(docs.count(), 1)
        self.assertEqual(docs.first(), doc)


class EmaDocumentModelTestCase(BaseTestCase):
    def setUp(self) -> None:
        super().setUp()

    def test_delete(self):
        doc = EmaDocument.objects.create(
            date_of_creation=now().date(),
            instance=self.ema,
            comment="TEST"
        )
        self.ema.refresh_from_db()
        docs = self.ema.get_documents()
        self.assertEqual(docs.count(), 1)
        self.assertEqual(docs.first(), doc)

        doc_title = doc.title
        doc.delete(user=self.superuser)
        last_log = self.ema.log.first()
        self.assertEqual(last_log.action, UserAction.EDITED)
        self.assertEqual(last_log.user, self.superuser)
        self.assertEqual(last_log.comment, DOCUMENT_REMOVED_TEMPLATE.format(doc_title))

        docs = self.ema.get_documents()
        self.assertEqual(docs.count(), 0)

