from intranet.search.core.snippets.femida import ProblemSnippet
from intranet.search.core.sources.femida.base import SourceBase
from intranet.search.core.sources.utils import get_text_content, get_short_desc


class Source(SourceBase):
    list_api = 'list'
    item_api = 'problem'
    item_url = 'problem_html'

    def do_create(self, result, **kwargs):
        summary = result['summary']
        solution = get_text_content(result['formatted_solution'])
        description = get_text_content(result['formatted_description'])
        cats = [i['name'] for i in result['categories']]
        url = self.get_doc_url(result)
        creator = result['created_by']

        def get_last_name(first_name, full_name):
            if first_name not in full_name:
                return ''

            _, _, last_name = full_name.partition(first_name)
            return last_name.strip()

        author = {
            'login': creator['username'],
            'first_name': creator['firstname'],
            'last_name': get_last_name(creator['firstname'], creator['fullname']),
        }

        body = {
            'solution': solution,
            'description': description,

            'z_ns_hidden': {
                'summary': summary,
                'categories': cats,
                'author': author,
            },
        }

        snippet = {
            'id': result['id'],
            'url': url,
            'title': summary,
            'description': get_short_desc(description, 200),
            'person': author,
            'solution': get_short_desc(solution, 200),
            'categories': result['categories'],
        }

        doc = self.create_document(url)

        doc.emit_snippet(ProblemSnippet(snippet), 'ru')
        doc.emit_body(body)

        for cat in result['categories']:
            doc.emit_facet_attr('category', cat['id'], label=cat['name'])

        doc.emit_facet_attr('author', creator['username'], creator['fullname'])

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