from haystack import indexes
from html2text import html2text

from .models import Post


class PostIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.EdgeNgramField(model_attr="title")
    body = indexes.EdgeNgramField(model_attr="body", null=True)
    status = indexes.EdgeNgramField(model_attr="status")
    date = indexes.DateField()
    agenda = indexes.EdgeNgramField(null=True)
    protocol = indexes.EdgeNgramField(null=True)

    def get_model(self):
        return Post

    def index_queryset(self, using=None):
        return self.get_model().objects.date_sorted_list(public=False)

    def prepare_date(self, obj):
        if obj.post_type == "N":
            return obj.public_date
        elif obj.post_type == "E":
            return obj.event_start.date()
        elif obj.post_type == "F":
            return obj.event_start.date()

    def prepare_agenda(self, obj):
        if obj.has_agenda and obj.agenda_html:
            return html2text(obj.agenda_html)
        return None

    def prepare_protocol(self, obj):
        if obj.has_protocol and obj.protocol_html:
            return html2text(obj.protocol_html)
        return None
