from logging import getLogger

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

log = getLogger(__name__)


class Source(SourceBase):
    """ Индексатор пакетов
    """
    source = 'packages'
    source_label = 'пакет'
    source_label_plural = 'пакеты'
    stat_factor_prefix = 'package'
    snippet_class = PackagesSnippet

    def do_fetch(self, obj, **kwargs):
        kwargs = {
            'tags': self.fetch_related(obj, 'tags'),
            'repos': self.fetch_related(obj, 'repos'),
            'services': self.fetch_related(obj, 'services'),
            'preservices': self.fetch_related(obj, 'preservices'),
            'workflows': self.fetch_related(obj, 'workflows'),
        }
        if kwargs['workflows']:
            kwargs['projects'] = [self.fetch_related_one(w, 'project') for w in kwargs['workflows']]
        self.next('create', obj=obj, **kwargs)

    def create_body(self, obj, **kwargs):
        data = obj['attributes']
        body = {
            'description': data['description'] or '',
        }
        hidden = {
            'name': data['name'],
            'emails': {
                'mailto': data['mailto'] or '',
            }
        }

        for field in ('tags', 'repos', 'workflows', 'projects', 'services', 'preservices'):
            hidden['related_%s' % field] = [t['attributes']['name'] for t in kwargs.get(field, [])]

        body['hidden'] = hidden
        return body

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

        for field in ('deleted', 'install_delay', 'version_named',
                      'replace_dots', 'upgrade_only', 'strip_version_build',
                      'version_delimited', 'deploy_scope', 'comment_required'):
            snippet[field] = obj['attributes'][field]

        versions = kwargs.get('versions', {})
        if versions:
            snippet['versions'] = {
                'stable': versions['stable']['version'],
                'testing': versions['stable']['version']
            }
        for field in ('tags', 'repos', 'workflows', 'projects', 'services', 'preservices'):
            snippet[field] = [self.dump_related(p) for p in kwargs.get(field, [])]
        return snippet

    def emit_factors(self, doc, obj):
        super().emit_factors(doc, obj)

        if obj['attributes']['deleted']:
            doc.emit_factor('isDeleted', 1)
