from logging import getLogger

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

log = getLogger(__name__)


class Source(SourceBase):
    """ Индексатор тикетов
    """
    source = 'tickets'
    source_label = 'тикет'
    source_label_plural = 'тикеты'
    stat_factor_prefix = 'ticket'
    snippet_class = TicketSnippet

    def do_fetch(self, obj, **kwargs):
        kwargs = {
            'author': self.fetch_related_one(obj, 'author'),
            'tasks': self.fetch_related(obj, 'tasks') or [],
            'packages': self.fetch_related(obj, 'packages') or [],
        }
        self.next('create', obj=obj, **kwargs)

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

    def create_body(self, obj, **kwargs):
        data = obj['attributes']
        body = {
            'comment': data['comment'],
        }
        hidden = {
            'status': data['status'],
            'branch': data['branch'],
            'author': kwargs['author']['attributes']['login'] if kwargs['author'] else ''
        }

        hidden['related_packages'] = [p['attributes']['name'] for p in kwargs.get('packages', [])]
        hidden['related_tasks'] = []
        for task in kwargs.get('tasks', []):
            hidden['related_tasks'].append({
                'related_tasks_name': task['attributes']['name'],
                'related_tasks_message': task['attributes']['message']})

        body['hidden'] = hidden
        return body

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

        for field in ('status', 'comment', 'branch'):
            snippet[field] = obj['attributes'][field]
        snippet['author'] = kwargs['author']['attributes']['login'] if kwargs['author'] else ''

        for field in ('tasks', 'packages'):
            snippet[field] = [self.dump_related(p) for p in kwargs.get(field, [])]
        return snippet
