import logging

from intranet.search.core.snippets.directory import DepartmentSnippet
from intranet.search.core.sources.directory.base import SourceBase
from intranet.search.core.sources.directory.client import join_fields
from intranet.search.core.sources.utils import get_by_lang, get_document_url, get_person_name_by_lang, \
    hash_factor

log = logging.getLogger(__name__)


class Source(SourceBase):
    """ Индексатор департаментов директории
    """
    doc_type = 'department'

    _department_fields = (
        'id',
        'name',
        'label',
        'email',
        'description',
        'external_id',
        'members_count',
        'removed',
        'aliases',
    )
    _head_fields = (
        'id',
        'name',
        'nickname',
    )
    _parent_fields = (
        'name',
    )

    FIELDS = join_fields((
        join_fields(_department_fields),
        join_fields(_head_fields, prefix='head'),
        join_fields(_parent_fields, prefix='parent'),
    ))

    def _request_directory(self, page=1):
        """ Не возвращает ничего, начиная с ISEARCH-7356
        """
        params = {'page': page, 'fields': self.FIELDS}
        if self.options['keys']:
            params['parent_id'] = ','.join(self.options['keys'])
        return self.api_client.get_departments(self.org_directory_id, **params)

    def fetch_object(self, obj_id):
        return self.api_client.get_department(obj_id, self.org_directory_id, fields=self.FIELDS)

    def do_create(self, obj, **kwargs):
        if obj['removed']:
            self.do_delete(obj)
        else:
            super().do_create(obj, **kwargs)

    def create_body(self, obj, **kwargs):
        body = {
            'name': obj['name'],
            'description': obj['description'],
            'label': obj['label'],
            'email': obj['email'],
            'external_id': obj['external_id'],
        }
        if obj['parent']:
            body['parent'] = {'name': obj['parent']['name']}
        return body

    def emit_factors(self, doc, obj):
        doc.emit_factor('isDepartment', 1)
        doc.emit_factor('urlHash', hash_factor(doc.url))

    def emit_attrs(self, doc, obj):
        if obj['label']:
            doc.emit_suggest_attr(obj['label'])
        for lang in ('ru', 'en'):
            name = get_by_lang(obj['name'], lang)
            if name:
                doc.emit_suggest_attr(name)
        for alias in obj['aliases'] or []:
            doc.emit_suggest_attr(alias)

    def create_snippet(self, obj, lang='ru', **kwargs):
        data = {
            'doc_type': self.doc_type
        }
        for f in ('id', 'label', 'email', 'members_count'):
            data[f] = obj[f]
        for f in ('name', 'description'):
            data[f] = get_by_lang(obj[f], lang)
        if obj['head']:
            data['head'] = {
                'uid': obj['head']['id'],
                'login': obj['head']['nickname'],
                'name': get_person_name_by_lang(obj['head'], lang),
                'url': get_document_url('users').format(login=obj['head']['nickname'])
            }

        return DepartmentSnippet(data)
