"""Product app documents."""
from django.conf import settings
from django_elasticsearch_dsl import Document, Index, fields
from tag import models
from news.models import News

TagCategoryIndex = Index(settings.ELASTICSEARCH_INDEX_NAMES.get(__name__, 'tag_category'))
TagCategoryIndex.settings(number_of_shards=2, number_of_replicas=2)


@TagCategoryIndex.doc_type
class TagCategoryDocument(Document):
    """TagCategory document."""

    tags = fields.ListField(fields.ObjectField(
        properties={
            'id': fields.IntegerField(),
            'value': fields.KeywordField(),
        },
    ))

    class Django:
        model = models.TagCategory
        fields = (
            'id',
            'index_name',
            'public',
            'value_type'
        )
        related_models = [models.Tag, News]


    def get_queryset(self):
        return super().get_queryset().with_base_related()

    def get_instances_from_related(self, related_instance):
        """If related_models is set, define how to retrieve the Car instance(s) from the related model.
        The related_models option should be used with caution because it can lead in the index
        to the updating of a lot of items.
        """
        if isinstance(related_instance, News):
            tag_categories = []
            for tag in related_instance.tags.all():
                if tag.category not in tag_categories:
                    tag_categories.append(tag.category)
            return tag_categories