from collections import deque

from haystack.forms import SearchForm
from haystack.query import SQ

from intern.models import Etherpad
from posts.models import Post


class FetUserSearchForm(SearchForm):
    def search(self):
        if not self.is_valid():
            return self.no_query_found()

        if not self.cleaned_data.get("q"):
            return self.no_query_found()

        sqs_post = self.searchqueryset.models(Post)
        sqs_post = sqs_post.filter(
            SQ(title__icontains=self.cleaned_data["q"])
            | SQ(body__icontains=self.cleaned_data["q"])
            | SQ(agenda__icontains=self.cleaned_data["q"])
            | SQ(protocol__icontains=self.cleaned_data["q"])
        )

        sqs_intern = self.searchqueryset.models(Etherpad)
        sqs_intern = sqs_intern.filter(etherpad__icontains=self.cleaned_data["q"])

        results = deque([])

        for elem in sqs_post.order_by("-date"):
            results.append(elem.object)

        for elem in sqs_intern.order_by("-date"):
            results.append(elem.object)

        return sorted(results, key=lambda elem: elem.date, reverse=True)


class NonUserSearchForm(SearchForm):
    def search(self):
        if not self.is_valid():
            return self.no_query_found()

        if not self.cleaned_data.get("q"):
            return self.no_query_found()

        sqs_post = self.searchqueryset.models(Post).filter(status="20")
        sqs_post = sqs_post.filter(
            SQ(title__icontains=self.cleaned_data["q"])
            | SQ(body__icontains=self.cleaned_data["q"])
            | SQ(agenda__icontains=self.cleaned_data["q"])
        )

        results = deque([])

        for elem in sqs_post.order_by("-date"):
            results.append(elem.object)

        return sorted(results, key=lambda elem: elem.date, reverse=True)
