import logging
import re

from intranet.search.core.utils import get_ids_repository
from intranet.search.core.swarm import Indexer


log = logging.getLogger(__name__)


class Source(Indexer):
    """ Индексатор переговорок
    """
    rooms_repo = get_ids_repository('staff', 'room')

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

    numbers = {
        '1': ['один', 'первый'],
        '2': ['два', 'второй'],
        '3': ['три', 'третий'],
        '4': ['четыре'],
        '5': ['пять'],
        '6': ['шесть'],
        '7': ['семь'],
    }

    def do_walk(self, **kwargs):
        rooms = self.rooms_repo.getiter(lookup={'type': 'conference'})
        for room in rooms:
            if room['is_deleted'] or room['floor']['office']['is_deleted']:
                self.do_delete(room)
            else:
                self.next('create', obj=room)

    def do_create(self, obj, **kwargs):
        search_url = self.gen_url(obj)
        doc = self.create_document(search_url)

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

        doc.emit_snippet(self.create_snippet(obj))
        names = list(self.gen_names(obj['name']['display']))
        for name in names:
            doc.emit_suggest_attr(name)
        for name_part in re.split(r'[\s.-_]+', obj['name']['display']):
            if len(name_part) > 1:
                doc.emit_suggest_attr(name_part)

        body = {
            'place': {
                'floor': obj['floor']['name'].get('ru'),
                'floor_en': obj['floor']['name'].get('en'),
                'office': obj['floor']['office']['name'],
            },
            'equipment': {k: [k, self.equipment_names[k]]
                          for k, v in obj['equipment'].items() if v},
            'phone': obj['phone'],
            'names': {
                'alternative': obj['name']['alternative'],
                'exchange': obj['name']['exchange'],
                'name': names,
            }
        }
        doc.emit_body(body)

        self.next('store', document=doc)

    def do_delete(self, obj, **kwargs):
        url = self.gen_url(obj)
        doc = self.create_document(url)
        self.next('store', document=doc, delete=True)

    def create_snippet(self, obj, lang='ru'):
        snippet = {
            'id': obj['id'],
            'name': obj['name']['display'],
            'name_alternative': obj['name']['alternative'],
            'name_exchange': obj['name']['exchange'],
            'phone': obj['phone'],
            'capacity': obj['capacity'],
            'map_url': 'http://staff.yandex-team.ru/map/#/conference_room/name_exchange/%s' %
                       obj['name']['exchange']
        }
        for k, v in obj['equipment'].items():
            snippet[k] = v
        snippet['floor_id'] = obj['floor']['id']
        if 'name' in obj['floor']:
            snippet['floor_name'] = obj['floor']['name'].get(lang)
        if 'id' in obj['floor']['office']:
            snippet['office_id'] = obj['floor']['office']['id']
            snippet['office_name'] = obj['floor']['office']['name'][lang]
        if obj['floor']['office']['city']:
            snippet['city_id'] = obj['floor']['office']['city']['id']
            snippet['city_name'] = obj['floor']['office']['city']['name'][lang]
        return snippet

    def gen_url(self, obj):
        return ('http://calendar.yandex-team.ru/event-add?invited={}'
                '%40yandex-team.ru').format(obj['name']['exchange'])

    def gen_names(self, name):
        yield name

        match = re.match(r'^(\d)\.(.+)', name, re.UNICODE)
        if match:
            num, sub_name = match.groups()
            if num in self.numbers:
                yield sub_name

                for item in self.numbers[num]:
                    yield item + ' ' + sub_name
