from django.views.generic import FormView
from django import forms

from intranet.search.core.utils.saas import get_metasearch_factors_for_url


class FactorForm(forms.Form):
    text = forms.CharField(label='Запрос')
    url = forms.CharField(label='URL')
    show_all_factors = forms.BooleanField(label='Показать все факторы', required=False, initial=False)


class FactorView(FormView):
    form_class = FactorForm
    template_name = 'isearch/search/factors.html'

    def form_valid(self, form):
        query = form.cleaned_data['text']
        url = form.cleaned_data['url']
        factors = get_metasearch_factors_for_url(query, url)
        if factors and not form.cleaned_data['show_all_factors']:
            factors = {key: value for key, value in factors.items() if value}
        context = self.get_context_data(form=form, factors=factors)
        return self.render_to_response(context)


factors_viewer = FactorView.as_view()
