import os
from pathlib import Path
from unittest import skipIf

from django.core.files import File
from django.test import RequestFactory, TestCase
from django.urls import reverse

from vbv_lernwelt.course.creators.test_utils import create_user
from vbv_lernwelt.media_files.models import UserImage

TEST_IMAGE = Path(__file__).parent / "test_images" / "user1_profile.jpg"


@skipIf(
    os.environ.get("ENABLE_S3_STORAGE_UNIT_TESTS") is None,
    "Only enable tests by setting ENABLE_S3_STORAGE_UNIT_TESTS=1",
)
class UserImageViewTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = create_user("supervisor")

        with open(TEST_IMAGE, "rb") as f:
            self.user_image, _ = UserImage.objects.get_or_create(
                file=File(f, name=TEST_IMAGE.name),
            )

    def test_image(self):
        # GIVEN
        self.client.force_login(self.user)

        # WHEN
        response = self._get_image(self.user_image.id, "fill-300x150")

        # THEN
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response["Content-Type"], "image/jpeg")

    def test_invalid_id(self):
        # GIVEN
        image_id = 123456789
        self.client.force_login(self.user)

        # WHEN
        response = self._get_image(image_id)

        # THEN
        self.assertEqual(response.status_code, 404)

    def test_invalid_filter(self):
        # GIVEN
        self.client.force_login(self.user)
        filter_spec = "invalid-filter"

        # WHEN
        response = self._get_image(self.user_image.id, filter_spec)

        # THEN
        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            response.content, f"Invalid filter spec: {filter_spec}".encode()
        )

    def _get_image(self, image_id, filter_spec=None):
        url = reverse("user_image", kwargs={"image_id": image_id})
        if filter_spec:
            url += f"?filter={filter_spec}"

        return self.client.get(url)
