"""This module contains the views of the ``django_discover`` app"""

from django.http import Http404, HttpResponse
from django.views.generic import ListView

from .constants import DISCOVER_ITEMS_ARCHIVE_NAME
from .models import DiscoverItem


class DiscoverItemsArchiveView(ListView):
    """Django List View returning an archive for the provided version"""

    model = DiscoverItem

    def get_queryset(self):
        """Filter the ``DiscoverItem``s accordingly to the url param "version".

        Raises
        ------
        Http404
            If the queryset is empty for the given version

        """

        queryset = super().get_queryset().for_version(
            *[
                int(version_part)
                for version_part in self.kwargs['version'].split('.')
            ]
        )

        if not queryset.exists():
            raise Http404

        return queryset

    def render_to_response(self, context, **response_kwargs):
        """Return a ZipFile containing the discover items"""

        zip_buffer = DiscoverItem.objects.get_zipped_discover_items(
            self.object_list
        )

        response = HttpResponse(content_type='application/x-zip-compressed')
        response['Content-Disposition'] = 'attachment; filename=%s' % DISCOVER_ITEMS_ARCHIVE_NAME

        response.write(zip_buffer.getvalue())

        return response
