from django.core.paginator import InvalidPage
from django.http import Http404

from wagtail.admin.views.generic.chooser import (
    BaseChooseView,
)

from .forms import FakeSearchFilterForm


# pylint: disable=abstract-method
class BaseSearchChooseView(BaseChooseView):
    ordering = True
    filter_form_class = FakeSearchFilterForm
    create_action_label = None
    elasticsearch_api_class = None

    def can_create(self):
        return False

    def apply_object_list_ordering(self, objects):
        return objects

    def consult_search_engine(self, request):
        self.filter_form.filter(None)

        page = int(request.GET.get("p", 1)) - 1
        from_ = self.per_page * page
        # pylint: disable=E1102
        result = (
            self.elasticsearch_api_class()
            .paginated_search(
                from_=from_,
                to=self.per_page,
                query_string=self.filter_form.search_query,
                search_type="cross_fields",
                search_operator="and",
                filters=[],
            )
            .page(page + 1)
        )
        # pylint: disable=attribute-defined-outside-init
        self.paginator = result.paginator

        return result

    def get_results_page(self, request):
        objects = self.get_object_list()
        objects = self.filter_object_list(objects)

        if self.filter_form.is_searching:
            return self.consult_search_engine(request)

        # pylint: disable=attribute-defined-outside-init
        self.paginator = self.paginator_class(objects, per_page=self.per_page)
        try:
            return self.paginator.page(request.GET.get("p", 1))
        except InvalidPage:
            raise Http404
