import json
import logging

from django import forms
from django.utils.translation import ugettext_lazy as _

from iconolab.conf import settings
from iconolab.models import Annotation, Collection, Item

from .indexes import AnnotationDocument, ItemDocument
from .query import EmptyQueryResults, QueryResults

logger = logging.getLogger(__name__)

class IconolabSearchForm(forms.Form):
    """
    Inspired by Haystack.forms.SearchForm
    """
    q = forms.CharField(required=False, label=_('Search'),
                        widget=forms.TextInput(attrs={'type': 'search'}))
    model_type = forms.ChoiceField(required=False, choices=(("images","Images"), ("annotations","Annotations")) )
    tags = forms.BooleanField(required=False, initial=False)

    def __init__(self, *args, **kwargs):
        self.collection_name = kwargs.pop("collection_name")
        selected_model_type =  kwargs.pop("model_type", None)

        if selected_model_type is not None:
            data = kwargs.get("data", None)
            if data:
                data = data.copy()
                data["model_type"] = selected_model_type
                kwargs['data'] = data

        super().__init__(*args, **kwargs)


    def search(self):

        model_type = self.cleaned_data.get('model_type')

        model_klass = None
        document_klass = None
        refine_qs = lambda qs: qs

        if(model_type == 'images'):
            model_klass = Item
            document_klass = ItemDocument
            refine_qs = lambda qs: qs.select_related('collection', 'metadatas')
        elif(model_type == 'annotations'):
            model_klass = Annotation
            document_klass = AnnotationDocument
            refine_qs = lambda qs: qs.select_related('image', 'image__item', 'image__item__collection', 'stats', 'current_revision', 'author')

        q = self.cleaned_data.get('q','')
        if model_klass is None or not q:
            return EmptyQueryResults()

        tags_only = self.cleaned_data.get("tags", False)
        fields = ['text'] if not tags_only else ['tags']

        el_qs = document_klass.search()

        if self.collection_name is not None:
            el_qs = el_qs.filter('term', collection=self.collection_name)

        el_qs = el_qs.query('simple_query_string', query=self.cleaned_data.get('q'), fields=fields)

        logger.debug("SEARCH : %s", json.dumps(el_qs.to_dict()))

        return QueryResults(el_qs, refine_qs)
