from __future__ import annotations

from typing import TYPE_CHECKING

from django.contrib.auth.decorators import permission_required

from django_spire.contrib.generic_views import portal_views

from ${module_path} import models
from ${module_path}.constants import LIST_FILTERING_SESSION_KEY
from ${module_path}.forms import ${model_class_name}ListFilterForm

if TYPE_CHECKING:
    from django.core.handlers.wsgi import WSGIRequest
    from django.template.response import TemplateResponse


@permission_required('${permission_prefix}.view_${model_instance_name}')
def ${list_items_view_name}(request: WSGIRequest) -> TemplateResponse:
    sort_field = request.GET.get('sort', 'name')
    sort_direction = request.GET.get('direction', 'asc')

    ${context_plural_var} = (
        models.${model_class_name}.objects
        .process_session_filter(
            request=request,
            session_key=LIST_FILTERING_SESSION_KEY,
            form_class=${model_class_name}ListFilterForm,
        ).order_by(
            f"{'-' if sort_direction == 'desc' else ''}{sort_field}"
        )
    )

    return portal_views.infinite_scrolling_view(
        request,
        context_data={'batch_size': 10,},
        queryset=${context_plural_var},
        queryset_name='${context_plural_var}',
        template='${template_directory_path}/table/${table_rows_template_name}.html'
    )
