from django.template.loader import render_to_string
from django.utils import timezone

from django_elasticsearch_dsl import DocType, Index, fields
from iconolab.conf import settings
from iconolab.models import (Annotation, AnnotationRevision, Collection, Item,
                             ItemMetadata)

__all__ = ['ItemDocument', 'AnnotationDocument']

def build_index(key):
    index_config = settings.ICONOLAB_INDEXES_CONFIG.get(key) or settings.ICONOLAB_INDEXES_DEFAULT_CONFIG
    index_name = index_config.pop('name', 'iconolab_' + key)
    index = Index(index_name)
    index.settings(**index_config)
    if settings.ICONOLAB_INDEXES_ANALYZER.get(key) is not None:
        index.analyzer(settings.ICONOLAB_INDEXES_ANALYZER.get(key))
    return index

def get_text_field_kwargs(key):
    analyzer = settings.ICONOLAB_INDEXES_FIELD_ANALYZER.get(key)
    if analyzer is not None:
        return {
            'analyzer': analyzer
        }
    else:
        return {}


items_index = build_index('items')

@items_index.doc_type
class ItemDocument(DocType):
    class Meta:
        model = Item

        queryset_pagination = settings.ICONOLAB_INDEXES_QUERYSET_PAGINATION
        related_models = [ItemMetadata]


    text = fields.TextField(**get_text_field_kwargs('items'))

    collection = fields.KeywordField(attr="collection.name")

    natural_key = fields.KeywordField(attr="metadatas.natural_key")


    def prepare_text(self, instance):
        return render_to_string('search/indexes/iconolab/item_text.txt', { 'object': instance })

    def get_queryset(self):
        return super().get_queryset().select_related('collection', 'metadatas').order_by('id')

    def get_instances_from_related(self, related_instance):
        if isinstance(related_instance, ItemMetadata):
            return related_instance.item
        else:
            return None



annotations_index = build_index('annotations')

@annotations_index.doc_type
class AnnotationDocument(DocType):

    class Meta:
        model = Annotation

        queryset_pagination = settings.ICONOLAB_INDEXES_QUERYSET_PAGINATION
        related_models = [ AnnotationRevision ]


    text = fields.TextField(**get_text_field_kwargs('annotations'))

    title = fields.TextField(attr="current_revision.title")
    description = fields.TextField(attr="current_revision.description")
    collection = fields.KeywordField(attr="image.item.collection.name")
    tags = fields.TextField(attr="tag_labels", multi=True)

    def prepare_text(self, instance):
        return render_to_string('search/indexes/iconolab/annotation_text.txt', { 'object': instance })

    def get_queryset(self):
        return super().get_queryset().filter(created__lte=timezone.now()).select_related('current_revision', 'image__item__collection').order_by('id')

    def get_instances_from_related(self, related_instance):
        if isinstance(related_instance, AnnotationRevision):
            return related_instance.annotation
        else:
            return None

