from django.http import JsonResponse
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import redirect

from oscar.core.loading import get_class

from .auth import oscar_auth
from .spooler import update_oscar_index as update_index_async

BaseCatalogueAutoCompleteView = get_class(
    "search.views.search", "CatalogueAutoCompleteView"
)


@oscar_auth
@staff_member_required
def update_oscar_index(request):
    update_index_async.spool()
    return redirect("/admin")


class OpenSearchAutocompleteView(BaseCatalogueAutoCompleteView):
    def get(self, request, *args, **kwargs):
        results = self.get_suggestions()
        return JsonResponse([self.request.GET.get("q"), results], safe=False)
