from haystack import indexes
from haystack.exceptions import NotHandled

from amanda.faq.models import Topic


class TopicIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.EdgeNgramField(document=True, use_template=True)
    created_at = indexes.DateTimeField()

    def get_model(self):
        return Topic

    def index_queryset(self, using=None):
        return self.get_model().objects.all()

    def should_update(self, instance, **kwargs):
        if instance.hidden:
            try:
                self.remove_object(instance)
            except NotHandled:
                pass
            return False
        else:
            return True

    def prepare_created_at(self, instance):
        return instance.created_at
