from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect
from django.views.generic import TemplateView
from django.views.generic.edit import FormView

from .forms import SearchForm


class SearchFormView(LoginRequiredMixin, FormView):
    template_name = "search/search.html"
    form_class = SearchForm

    def form_valid(self, form):
        return redirect("search", search=form.cleaned_data.get("search"))


class SearchView(LoginRequiredMixin, TemplateView):
    template_name = "search/search_results.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        _user = self.request.user

        context["form"] = SearchForm(initial={"search": self.kwargs["search"]})
        context["search"] = self.kwargs["search"]
        context["transactions"] = _user.transaction_set.search(self.kwargs["search"])
        context["accounts"] = _user.account_set.search(self.kwargs["search"])
        context["statements"] = _user.statement_set.search(self.kwargs["search"])
        context["categories"] = _user.category_set.search(self.kwargs["search"])
        context["invoices"] = _user.invoice_set.search(self.kwargs["search"])[:10]

        return context
