# -*- coding: utf-8 -*-
'''
Created on Feb 12, 2013

@author: ymh
'''

from haystack.backends import BaseEngine, elasticsearch_backend

from egonomy.models import Fragment


class ElasticsearchSearchBackend(elasticsearch_backend.ElasticsearchSearchBackend):

    def build_search_kwargs(self, query_string, sort_by=None, start_offset=0, end_offset=None,
                        fields='', highlight=False, facets=None,
                        date_facets=None, query_facets=None,
                        narrow_queries=None, spelling_query=None,
                        within=None, dwithin=None, distance_point=None,
                        models=None, limit_to_registered_models=None,
                        result_class=None):
        
        kwargs = super(ElasticsearchSearchBackend, self).build_search_kwargs(query_string, sort_by=sort_by, start_offset=start_offset, end_offset=end_offset,
                        fields=fields, highlight=highlight, facets=facets,
                        date_facets=date_facets, query_facets=query_facets,
                        narrow_queries=narrow_queries, spelling_query=spelling_query,
                        within=within, dwithin=dwithin, distance_point=distance_point,
                        models=models, limit_to_registered_models=limit_to_registered_models,
                        result_class=result_class)
                
        #TODO : try to make list of field dynamic
        #TODO : How to handle multiple
        if highlight:
            highlight_def = kwargs.get('highlight', {})
            fields_def = highlight_def.get('fields', {})
            
            if models is None or len(models) == 0 or Fragment in models:
                fields_def['tags'] = {}
                fields_def['title'] = {}
                fields_def['description'] = {}
            
            highlight_def.update({
                'pre_tags' : ["<span class='highlight'>"],
                'post_tags' : ["</span>"],
                "number_of_fragments" : 0,
                'fields': fields_def
            })
        
        return kwargs

class ElasticsearchSearchEngine(BaseEngine):
    backend = ElasticsearchSearchBackend
    query = elasticsearch_backend.ElasticsearchSearchQuery
