from django.utils.encoding import force_str

from .base import FormApiView
from ..forms import ApiArtefactForm


class FacetLabelsApiView(FormApiView):
    """ Получение списка значений фасетов
    """
    form_class = ApiArtefactForm

    def get_response_data(self, form):
        storage = form.get_storage('facets')
        facet = ''

        if form.name.data and form.values.data:
            facet = form.name.data
            facets = storage.get(facet=facet, value__in=form.values.data)
        else:
            facets = []

        res = {facet: {}}

        label_field = 'label_%s' % form.language.data
        an_label_field = 'label_%s' % ('ru' if form.language.data == 'en' else 'en')

        for entry in facets:
            label = entry[label_field] or entry[an_label_field]
            id_ = entry['value']
            res[facet][id_] = {
                'id': force_str(entry['id']),
                'value': force_str(entry['value']),
                'label': force_str(label),
            }
        return res
