# -*- coding: utf-8 -*-

from distribution import app
from . import BaseManager


class TaxonomyTopicManager(BaseManager):
    index = app.config.get('ELASTICSEARCH_TAXONOMY_INDEX_NAME', 'distribution_taxonomy')

    def search_by_name_and_type(self, name, topic_type):  # pragma: no cover
        query = {
            'post_filter': {
                'bool': {
                    'must': [
                        {
                            'term': {
                                'name': name
                            }
                        }
                    ]
                }
            }
        }

        if topic_type:
            query['post_filter']['bool']['must'].append({
                'term': {
                    'topic_type': topic_type
                }
            })

        return self.search(query)

    def get_with_descendants(self, topic_uuids, include_parents=True, max_depth=1):
        if len(topic_uuids) == 0:
            return []

        parents = self.mget(topic_uuids)

        children_uuids = []
        if max_depth:
            for parent in parents:
                children_uuids += parent.data['children']

        descendants = self.get_with_descendants(children_uuids, max_depth=max_depth-1)

        result = parents + descendants if include_parents else descendants
        return list(set(result))
