# -*- coding: utf-8 -*-
'''
Created on Sep 20, 2013

@author: ymh
'''
from haystack.forms import SearchForm

from p4l.models.data import Record
from p4l.search.query_parser import QueryParser
from p4l.utils import strip_accents


class RecordSearchForm(SearchForm):
    
    def __init__(self, *args, **kwargs):
        SearchForm.__init__(self, *args, **kwargs)
        
    def no_query_found(self):
        return self.searchqueryset.all()
    
    def search(self):
        if not self.is_valid():
            return self.no_query_found()

        if not self.cleaned_data.get('q'):
            return self.no_query_found()

        qp = QueryParser("text")
        sqs = self.searchqueryset.models(Record).filter(qp.parse(strip_accents(self.cleaned_data['q'])))

        if self.load_all:
            sqs = sqs.load_all()

        return sqs
