from haystack.generic_views import SearchView
from haystack.query import RelatedSearchQuerySet
from iconolab.search_indexes.forms import IconolabSearchForm
from django.shortcuts import HttpResponse, redirect
from django.core.urlresolvers import reverse
from django.views.generic import RedirectView
from iconolab.models import Collection

#override Search and Related QuerySet here
class IconolabSearchView(SearchView):
    form_class = IconolabSearchForm
    queryset = RelatedSearchQuerySet()
    template_name = "search/default_search.html"
    load_all = True

    templates_map = {
        "images": "search/image_search.html",
        "annotations": "search/annotation_search.html"
    }

    def complete_url(self, url, tags_only):
        query = self.request.GET.get("q", None)
        page = self.request.GET.get("page", None)

        queryargs = []
        query_string = ""

        if query is not None:
            queryargs.append("q=" + query)

        if page is not None:
            queryargs.append("page=" + page)

        if tags_only:
            queryargs.append("tags=1")

        if len(queryargs):
            query_string = "&".join(queryargs)
            url += "?" + query_string

        return url

    def get(self, request, *args, **kwargs):

        self.model_type = request.GET.get('model_type', None)
        self.paginate_by = request.GET.get('perpage', 10)
        collection_name = self.kwargs.get('collection_name', None)

        tags_only = False
        if (self.model_type == 'tags'):
            self.model_type = 'annotations'
            tags_only = True

        if self.model_type is not None:
            if collection_name is None:
                #redirect to all_model_type
                redirect_url = reverse('search_indexes:model_search', kwargs={'model_type': self.model_type})
                return redirect(self.complete_url(redirect_url, tags_only))
            else:
                redirect_url = reverse('search_indexes:collection_with_model_search', kwargs={'collection_name': collection_name, 'model_type':self.model_type})
                return redirect(self.complete_url(redirect_url, tags_only))
        else:
            has_error, redirectView = self.check_kwargs(**kwargs)
            if has_error:
                return redirectView(request)
            return super(IconolabSearchView, self).get(request, *args, **kwargs)

    def check_kwargs(self, **kwargs):
        result = (False, None)
        try:
            collection_name = kwargs.get('collection_name', None)
            if collection_name is None:
                return result
            collection = Collection.objects.get(name=kwargs.get('collection_name'))
        except Collection.DoesNotExist:
            result = (True, RedirectView.as_view(url=reverse('404error')))
        finally:
            return result

    def get_queryset(self):
        return IconolabSearchView.queryset

    def get_form_kwargs(self):
        kwargs = super(IconolabSearchView, self).get_form_kwargs()
        kwargs['collection_name'] = self.kwargs.get('collection_name', None)
        kwargs['model_type'] = self.kwargs.get('model_type', None)
        return kwargs

    def get_template_names(self):
        try :
            model_type = self.kwargs.get('model_type', None)
            template = IconolabSearchView.templates_map[model_type]
        except KeyError:
            template = IconolabSearchView.template_name
        finally:
            return [template]

    def get_context_data(self, *args, **kwargs):
        context = super(IconolabSearchView, self).get_context_data(*args, **kwargs)
        context['collection_name'] = self.kwargs.get('collection_name', '')
        return context
