import operator

from django import template
from django.forms.models import BaseModelForm

register = template.Library()

field_name = operator.attrgetter("name", "label")
gather_field_names = operator.attrgetter("form._meta.fields")
gather_model_fields = operator.attrgetter("form._meta.model._meta.fields")


@register.filter("visible_fieldnames")
def modelformset_visible_fieldnames(formset):
    if isinstance(formset, BaseModelForm):
        model_fields = gather_model_fields(formset)
        return [field_name(field) for field in model_fields if not field.is_hidden]
    elif formset.total_form_count():
        some_form = formset.forms[0]
        return map(field_name, some_form.visible_fields())

    return [(x, x) for x in gather_field_names(formset)]


@register.filter(name="zip")
def zip_lists(a, b):
    return zip(a, b)


@register.simple_tag(takes_context=True)
def method_price(context, method):
    basket = context.get("basket", None)
    if basket is not None:
        return {"price": method.calculate(basket)}

    return ""
