from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.views.generic import TemplateView

from wagtail.models import Locale

from ocyan.core.fender import config

from ocyan.plugin.wagtail.models import AbstractBasePage


class WagtailPageSearch(TemplateView):
    template_name = "ocyan_plugin_wagtail/search/results.html"

    def get_context_data(self, *args, **kwargs):
        q = self.request.GET.get("q")
        page = self.request.GET.get("page", 1)

        if q:
            current_locale = Locale.get_active()
            pages = (
                AbstractBasePage.objects.live()
                .filter(locale=current_locale)
                .search(
                    q,
                    fields=["search_title"],
                    operator=settings.WAGTAIL_SEARCH_QUERY_OPERATOR,
                )
            )
            paginator = Paginator(
                pages, config.get("oscar", "dashboard_items_per_page", 20)
            )
            # Try to get the ?page=x value
            try:
                # If the page exists and the ?page=x is an int
                page = paginator.page(page)
            except PageNotAnInteger:
                # If the ?page=x is not an int; show the first page
                page = paginator.page(1)
            except EmptyPage:
                # If the ?page=x is out of range (too high most likely)
                # Then return the last page
                page = paginator.page(paginator.num_pages)

            return {"page_obj": page, "paginator": paginator}
