from importlib import import_module

from django.conf import settings
from .isearch_serializers import get_work_phone  # noqa: UnusedImport

serializer_module = import_module(f'intranet.search.abovemeta.serializers.{settings.APP_NAME}_serializers')


def default_suggest_serializer(snippet, doc):
    return {
        'id': str(snippet['id']),
        'url': snippet['url'],
        'title': snippet['name'],
        'fields': []
    }


def default_search_serializer(snippet, doc):
    if not snippet.get('url'):
        snippet['url'] = doc.url
    return snippet


def suggest_serializer_fabric(layer):
    """ Фабрика получения сериализаторов для саджеста

    :param layer: название слоя в саджесте
    :return: функцию для сериализации
    """
    layer_name = layer.replace('-', '_')
    return getattr(serializer_module, f'suggest_{layer_name}_serializer', default_suggest_serializer)


def search_serializer_fabric(search, index, scope):
    """ Фабрика для получения сериализаторов для саджеста

    :return:
    """
    name_with_scope = '_'.join(filter(None, [scope, search, index]))
    name = '_'.join(filter(None, [search, index]))

    for name in (name_with_scope, name):
        serializer_name = f'search_{name}_serializer'
        serializer = getattr(serializer_module, serializer_name, None)
        if serializer is not None:
            return serializer

    return default_search_serializer
