import datetime

from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase
from wagtail.models import Collection

from vbv_lernwelt.core.create_default_users import create_default_users
from vbv_lernwelt.core.models import User
from vbv_lernwelt.media_files.models import ContentDocument

TITLE = "Musterlösung Fahrzeug"


class TestContentDocumentServing(TestCase):
    def setUp(self):
        create_default_users()
        now_str = str(datetime.datetime.now().strftime("%d-%m-%Y-%H-%M"))
        collection, _ = Collection.objects.get_or_create(name="Root", depth=0)
        document = ContentDocument.objects.create(
            title=TITLE,
            display_text="Musterlösung Fahrzeug",
            description="Musterlösung für den Auftrag Fahrzeug",
            link_display_text="Dokument laden",
            file=SimpleUploadedFile(
                f"testdocument_{now_str}.txt", b"these are the file contents!"
            ),
            collection=collection,
        )
        document.save()

    def test_download_document_from_wagtail_logged_in_user_200(self):
        self.user = User.objects.get(username="admin")
        self.client.login(username="admin", password="test")
        document = ContentDocument.objects.get(title=TITLE)
        client = self.client

        self.assertEqual(
            document.url, f"/server/documents/{document.id}/{document.filename}"
        )

        response = client.get(document.url)
        self.assertEqual(response.status_code, 200)

    def test_download_document_from_wagtail_anonymous_user_redirect_to_login(self):
        document = ContentDocument.objects.get(title=TITLE)
        self.client.logout()
        response = self.client.get(document.url)
        self.assertEqual(response.status_code, 302)
        self.assertTrue("login" in response.url)
