from logging import getLogger

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

log = getLogger(__name__)


class Source(SourceBase):
    """ Индексатор воркфлоу
    """
    source = 'workflows'
    source_label = 'воркфлоу'
    source_label_plural = 'воркфлоу'
    stat_factor_prefix = 'workflow'
    snippet_class = WorkflowSnippet

    def do_fetch(self, obj, **kwargs):
        kwargs = {
            'project': self.fetch_related_one(obj, 'project') or {},
            'deploy_groups': self.fetch_related_one(obj, 'deploy_groups') or {},
        }
        self.next('create', obj=obj, **kwargs)

    def create_body(self, obj, **kwargs):
        data = obj['attributes']
        body = {
            'comment': data['comment'] or '',
            'hidden': {
                'name': data['name'],
            }
        }
        if kwargs['project']:
            body['hidden']['related_project'] = {
                'project_name': kwargs['project']['attributes']['name'],
                'project_description': kwargs['project']['attributes']['description'],
            }
        return body

    def create_snippet(self, obj, lang='ru', **kwargs):
        snippet = super().create_snippet(obj, lang, **kwargs)
        snippet['comment'] = obj['attributes']['comment'] or ''
        if kwargs.get('project'):
            snippet['project'] = self.dump_related(kwargs.get('project'))
        if kwargs.get('deploy_groups'):
            snippet['deploy_groups'] = []
            for group in kwargs['deploy_groups']:
                grp = self.dump_related(group)
                grp['repo_branch'] = group['attributes']['repo_branch']
                snippet['deploy_groups'].append(grp)
        return snippet
