import logging
from django.conf import settings

from intranet.search.core.sources.map.map import BaseRoomIndexer
from intranet.search.core.snippets.map import ConferenceSnippet
from intranet.search.core.sources.map.utils import get_enumerated_name, number_to_words


log = logging.getLogger(__name__)


class Source(BaseRoomIndexer):
    """
    Индексатор переговорок
    """

    def __init__(self, options, *args, **kwargs):
        self.conferences_url = settings.ISEARCH['map']['urls']['conferences']
        self.map_url = settings.ISEARCH['map']['urls']['conferences_map']

        self.equipment_names = {
            'cork_board': 'Пробковая доска',
            'desk': 'Стол',
            'game_console': 'Игровая приставка',
            'marker_board': 'Маркерная доска',
            'projector': 'Проектор',
            'screen': 'ЖК панель',
            'seats': '',
            'video_conferencing': 'Видеосвязь',
            'voice_conferencing': 'Конференц-связь',
            'guest_wifi': 'Гостевой wi-fi',
        }
        super().__init__(options, *args, staff_repo_name='room', **kwargs)

    @property
    def searched_type(self):
        return {'ru': 'переговорка', 'en': 'conference'}

    def do_walk(self, **kwargs):
        super().do_walk(room_type='conference')

    def create_body(self, obj):
        body = self.base_body(obj)
        existing_equipment = {}
        for eq_name, eq_available in obj['equipment'].items():
            if eq_available:
                existing_equipment[eq_name] = [eq_name, self.equipment_names[eq_name]]
        additional_fields = {
            'equipment': existing_equipment,
            'phone': obj['phone'],
        }
        body |= additional_fields
        return body

    def emit_additional_attributes(self, doc, obj):
        if obj['phone']:
            try:
                doc.emit_search_attr('i_phone', int(obj['phone']))
            except ValueError:
                search_url = self.gen_url(obj)
                log.exception('Wrong phone for %s', search_url)

    def create_snippet(self, obj, lang='ru'):
        snippet = self.base_snippet(obj, lang)
        additional_fields = {
            'name_alternative': obj['name']['alternative'],
            'name_exchange': obj['name']['exchange'],
            'phone': obj['phone'],
            'capacity': obj.get('capacity') or '0',
        }
        snippet |= additional_fields
        snippet['equipment'] = obj['equipment']
        return ConferenceSnippet(snippet)

    def gen_url(self, obj):
        return self.conferences_url.format(obj['name']['exchange'])

    def gen_names(self, name):
        possible_names = [name]
        enumerated_name = get_enumerated_name(name)
        if enumerated_name:
            num, sub_name = enumerated_name.groups()
            num_words = number_to_words(num)
            if len(num_words) > 0:
                possible_names.append(sub_name)
                for item in num_words:
                    possible_names.append(item + ' ' + sub_name)
        return possible_names

    def gen_map_url(self, obj):
        map_url = self.map_url.format(obj['name']['exchange'])
        return map_url
