from django.http import HttpResponse, HttpRequest
from django.shortcuts import render
from django.core.paginator import Paginator
from django.db.models import Q

from apps.gnous_eu.models import Service

TEMPLATE_PATH = "./"


class ServicesView:
    @staticmethod
    def index(request: HttpRequest, *args, **kwargs) -> HttpResponse:
        search: str = request.GET.get("search", False)

        if search:
            data_services = Service.objects.all().filter(
                Q(id__exact=int(search) if search.isdigit() else 0)
                | Q(name__icontains=search)
                | Q(description__icontains=search)
                | Q(sources__icontains=search)
                | Q(hosted__icontains=search)
                | Q(domain__icontains=search)
                | Q(sources__icontains=search)
                | Q(hosted__icontains=search)
            )
        else:
            data_services = Service.objects.all().filter(hidden=False)
        paginator = Paginator(data_services, 30)

        page = request.GET.get("page")

        return render(
            request,
            TEMPLATE_PATH + "services.html",
            {"services": paginator.get_page(page), "search": search},
        )
