from intranet.search.core.snippets.conductor import HostsSnippet
from intranet.search.core.sources.conductor.base import SourceBase


class Source(SourceBase):
    """ Индексатор хостов
    """
    source = 'hosts'
    source_label = 'хост'
    source_label_plural = 'хосты'
    stat_factor_prefix = 'host'
    need_fetch = True
    snippet_class = HostsSnippet

    def do_fetch(self, obj, **kwargs):
        kwargs = {
            'group': self.fetch_related_one(obj, 'group'),
            'tags': self.fetch_related(obj, 'tags'),
            'datacenter': self.fetch_related_one(obj, 'datacenter')
        }

        if kwargs['datacenter']:
            kwargs['datacenter']['attributes']['parent'] = self.fetch_related_one(
                kwargs['datacenter'], 'parent')

        self.next('create', obj=obj, **kwargs)

    def create_body(self, obj, **kwargs):
        data = obj['attributes']
        body = {
            'short_name': data['short_name'],
            'description': data['description'],
            'related_group': {
                'group_name': kwargs['group']['attributes']['name'] if kwargs['group'] else '',
            },
        }
        hidden = {
            'name': data['fqdn'],
        }
        if kwargs.get('tags'):
            hidden['related_tags'] = [t['attributes']['name'] for t in kwargs['tags']]

        if kwargs.get('datacenter'):
            dc = kwargs['datacenter']
            hidden['related_dc'] = {
                'dc_name': dc['attributes']['name'],
                'dc_golem_name': dc['attributes']['golem_name'],
            }
            parent = dc['attributes']['parent']
            if parent:
                hidden['related_dc']['parent'] = {
                    'parent_dc_name': parent['attributes']['name'],
                    'parent_dc_golem_name': parent['attributes']['golem_name'],
                }

        body['hidden'] = hidden
        return body

    def create_snippet(self, obj, lang='ru', **kwargs):
        snippet = super().create_snippet(obj, lang, **kwargs)

        snippet['group'] = self.dump_related(kwargs['group'])
        if kwargs.get('datacenter'):
            snippet['datacenter'] = self.dump_related(kwargs['datacenter'])

        if kwargs.get('tags'):
            snippet['tags'] = [self.dump_related(t) for t in kwargs['tags']]

        return HostsSnippet(snippet)

    def get_obj_name(self, obj):
        return obj['attributes']['fqdn']
