import crispy_forms
from crispy_forms import layout
from crispy_forms.utils import TEMPLATE_PACK
from django.template.loader import render_to_string


class OrderableFormset(layout.Div):
    template = 'crispy_layouts/layout/orderable-formset.html'

    def __init__(self, formset_context_variable, *fields, css_class='', add_form_next_to_label=False, **kwargs):
        self.formset_context_variable = formset_context_variable
        self.css_class = css_class
        self.add_form_next_to_label = add_form_next_to_label
        super().__init__(*fields, **kwargs)

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
        # fields = self.get_rendered_fields(form, form_style, context, template_pack, **kwargs)
        template = self.get_template_name(template_pack)
        formset = context.get(self.formset_context_variable)
        if formset:
            return render_to_string(
                template, {
                    'div': self,
                    'formset': formset,
                    'css_class': self.css_class,
                    'add_form_next_to_label': self.add_form_next_to_label,
                }
            )
        else:
            return '<!-- missing `{}` in context -->'.format(self.formset_context_variable)
