import imghdr
from wsgiref.util import FileWrapper

import structlog
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, StreamingHttpResponse
from django.shortcuts import get_object_or_404
from wagtail.images.exceptions import InvalidFilterSpecError
from wagtail.images.models import SourceImageIOError

from vbv_lernwelt.media_files.models import UserImage

logger = structlog.get_logger(__name__)


@login_required
def user_image(request, image_id):
    image = get_object_or_404(UserImage, id=image_id)

    filter_spec = request.GET.get("filter", "original")

    try:
        rendition = image.get_rendition(filter_spec)
    except SourceImageIOError:
        return HttpResponse(
            "Source image file not found", content_type="text/plain", status=410
        )
    except InvalidFilterSpecError:
        return HttpResponse(
            "Invalid filter spec: " + filter_spec,
            content_type="text/plain",
            status=400,
        )

    rendition.file.open("rb")
    image_format = imghdr.what(rendition.file)

    return StreamingHttpResponse(
        FileWrapper(rendition.file),
        content_type=f"image/{image_format}" if image_format else "binary/octet-stream",
    )
