import emoji
from django.core.paginator import PageNotAnInteger, EmptyPage
from django.shortcuts import render

from ..filters import SearchEventFilter, SimpleSearchEventFilter
from ..models import (
    Category,
    remove_accents,
    Event,
    Place,
    Organisation,
    RecurrentImport,
)
from ..views import get_event_qs
from django.db.models import Q, F, Func


def event_search(request, full=False):
    from .utils import PaginatorFilterCountless

    categories = None
    tags = None
    places = None
    organisations = None
    rimports = None

    qs = get_event_qs(request).order_by("-start_day")
    if not request.user.is_authenticated:
        qs = qs.filter(
            (
                Q(other_versions__isnull=True)
                | Q(other_versions__representative=F("pk"))
                | Q(other_versions__representative__isnull=True)
            )
        )
    if full:
        filter = SearchEventFilter(
            request.GET,
            queryset=qs,
            request=request,
        )
    else:
        filter = SimpleSearchEventFilter(
            request.GET,
            queryset=qs,
            request=request,
        )
        if "q" in request.GET:
            categories = Category.objects.filter(name__icontains=request.GET["q"])
            s_q = remove_accents(request.GET["q"].lower())
            tags = (
                Event.objects.extra(
                    where=["%s ILIKE ANY (tags)"], params=[request.GET["q"]]
                )
                .annotate(arr_tags=Func(F("tags"), function="unnest"))
                .values_list("arr_tags", flat=True)
                .distinct()
            )
            tags = [
                (
                    t,
                    emoji.demojize(remove_accents(t).lower(), delimiters=("000", "")),
                )
                for t in tags
            ]
            tags = [t for t in tags if s_q == t[1]]
            tags.sort(key=lambda x: x[1])
            tags = [t[0] for t in tags]
            places = Place.objects.filter(
                Q(name__icontains=request.GET["q"])
                | Q(description__icontains=request.GET["q"])
                | Q(city__icontains=request.GET["q"])
            )
            organisations = Organisation.objects.filter(
                Q(name__icontains=request.GET["q"])
                | Q(description__icontains=request.GET["q"])
            )
            if request.user.is_authenticated:
                rimports = RecurrentImport.objects.filter(
                    name__icontains=request.GET["q"]
                )

    paginator = PaginatorFilterCountless(filter, 10, request)
    page = request.GET.get("page")

    try:
        response = paginator.page(page)
    except PageNotAnInteger:
        response = paginator.page(1)
    except EmptyPage:
        response = paginator.page(paginator.num_pages)

    return render(
        request,
        "agenda_culturel/search.html",
        {
            "filter": filter,
            "categories": categories,
            "tags": tags,
            "places": places,
            "organisations": organisations,
            "rimports": rimports,
            "has_results": len(request.GET) != 0
            or (len(request.GET) > 1 and "page" in request.GET),
            "paginator_filter": response,
            "full": full,
        },
    )


def event_search_full(request):
    return event_search(request, True)
