class Layout(crispy_forms_layout.Layout):
    pass class Fieldset(crispy_forms_layout.Fieldset):
    """
    It wraps fields in a ``<fieldset>``:

    .. sourcecode:: python

        Fieldset("Text for the legend",
            'form_field_1',
            'form_field_2'
        )

    The first parameter is the text for the fieldset legend. This text is
    context aware, so you can do things like :

    .. sourcecode:: python

        Fieldset("Data for {{ user.username }}",
            'form_field_1',
            'form_field_2'
        )
    """
    template = "%s/layout/fieldset.html" class TabItem(Container):
    """
    Tab item object. It wraps fields in a div whose default class is "tabs" and
    takes a name as first argument.

    Tab item is also responsible of building its associated tab link with its
    ``render_link`` using the ``link_template`` attribute.

    Example:

    .. sourcecode:: python

        TabItem('My tab', 'form_field_1', 'form_field_2', 'form_field_3')

    ``TabItem`` layout item has no real utility out of a ``TabHolder``.
    """
    template = "%s/layout/tab-item.html"
    link_template = "%s/layout/tab-link.html"

    def has_errors(self, form):
        """
        Find tab fields listed as invalid
        """
        return any([fieldname_error for fieldname_error in form.errors.keys()
                    if fieldname_error in self])

    def render_link(self, form, template_pack=TEMPLATE_PACK, **kwargs):
        """
        Render the link for the tab-pane. It must be called after render so
        ``css_class`` is updated with ``active`` class name if needed.
        """
        link_template = self.link_template % template_pack
        return render_to_string(link_template,
                                {
                                    'link': self,
                                    'item_has_errors': self.has_errors(form)
                                }) class TabHolder(crispy_forms_bootstrap.TabHolder):
    """
    Tabs holder object to wrap Tab item objects in a container:

    .. sourcecode:: python

        TabHolder(
            TabItem('My tab 1', 'form_field_1', 'form_field_2'),
            TabItem('My tab 2', 'form_field_3')
        )

    ``TabHolder`` direct children should allways be a ``TabItem`` layout item.

    A random id is builded for the tab holder if you don't define it using
    ``css_id`` argument.

    The first ``TabItem`` containing a field error will be marked as
    *active* if any, else this will be just the first ``TabItem``.
    """
    template = "%s/layout/tab-holder.html"
    default_active_tab = None

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK):
        """
        Re-implement almost the same code from crispy_forms but passing
        ``form`` instance to item ``render_link`` method.
        """
        links, content = '', ''

        # accordion group needs the parent div id to set `data-parent` (I don't
        # know why). This needs to be a unique id
        if not self.css_id:
            self.css_id = "-".join(["tabsholder", str(randint(1000, 9999))])

        for tab in self.fields:
            tab.active = False

        # Activate item
        self.open_target_group_for_form(form)

        for tab in self.fields:
            content += render_field(
                tab, form, form_style, context, template_pack=template_pack
            )
            links += tab.render_link(form, template_pack)

        context.update({
            'tabs': self,
            'links': links,
            'content': content
        })

        template = self.get_template_name(template_pack)
        return render_to_string(template, context.flatten()) class AccordionItem(crispy_forms_bootstrap.AccordionGroup):
    """
    Accordion item object. It wraps given fields inside an accordion
    tab. It takes accordion tab name as first argument.

    The item name is also slugified to build an id for the tab if you don't
    define it using ``css_id`` argument.

    Example:

    .. sourcecode:: python

        AccordionItem("group name", "form_field_1", "form_field_2")
    """
    template = "%s/layout/accordion-item.html" class AccordionHolder(crispy_forms_bootstrap.Accordion):
    """
    Accordion items holder object to wrap Accordion item objects in a
    container:

    .. sourcecode:: python

        AccordionHolder(
            AccordionItem("group name", "form_field_1", "form_field_2"),
            AccordionItem("another group name", "form_field"),
        )

    ``AccordionHolder`` direct children should allways be a ``AccordionItem``
    layout item.

    A random id is builded for the accordion holder if you don't define it
    using ``css_id`` argument.

    The first ``AccordionItem`` containing a field error will be marked as
    *active* if any, else this will be just the first ``AccordionItem``.
    """
    template = "%s/layout/accordion-holder.html"

    def render(self, form, form_style, context, template_pack=TEMPLATE_PACK,
               **kwargs):
        """
        Re-implement almost the same code from crispy_forms but using
        ``form`` instance to catch field errors.
        """
        content = ''

        # accordion group needs the parent div id to set `data-parent` (I don't
        # know why). This needs to be a unique id
        if not self.css_id:
            self.css_id = "-".join(["accordion",
                                    str(randint(1000, 9999))])

        # Active first 'AccordionItem' containing a field error if any, else
        # active first holder item
        self.open_target_group_for_form(form)

        for group in self.fields:
            group.data_parent = self.css_id
            group.item_has_errors = any([fieldname_error for fieldname_error in
                                         form.errors.keys()
                                         if fieldname_error in group])
            content += render_field(
                group, form, form_style, context, template_pack=template_pack,
                **kwargs
            )

        template = self.get_template_name(template_pack)
        context.update({'accordion': self, 'content': content})

        return render_to_string(template, context.flatten()) def part_1_crispies(pack=None):
    return [
        Row(
            Column('full_input'),
        ),
        Row(
            Column(
                Row(
                    Column(
                        'column_input_1',
                        css_class='large-4'
                    ),
                    Column(
                        'column_input_2',
                        css_class='large-4'
                    ),
                    Column(
                        'column_input_3',
                        css_class='large-4'
                    ),
                )
            ),
        ),
    ] def part_2_crispies(pack=None):
    return [
        Row(
            Column(
                'select_input',
                css_class='large-12'
            ),
        ),
        Row(
            Column(
                'radio_input',
                css_class='large-4'
            ),
            Column(
                'checkbox_input',
                css_class='large-4'
            ),
            Column(
                Row(
                    Column(
                        SwitchField('checkbox_switch_input_1', switch_class="round tiny"),
                        css_class='small-3'
                    ),
                    Column(
                        HTML('<label>Checkbox with a switch field</label>'),
                        css_class='small-9'
                    ),
                ),
                Row(
                    Column(
                        InlineSwitchField('checkbox_switch_input_2'),
                    ),
                ),
                css_class='large-4'
            ),
        ),
    ] def part_3_crispies(pack=None):
    return [
        Row(
            Column('textarea_input'),
        ),
    ] def part_4_crispies(pack=None):
    return [
        InlineField('inlinefield_input'),
        InlineJustifiedField('inlinejustifiedfield_input'),
    ] def buttons_crispies(pack=None):
    return [
        Row(
            Column(
                ButtonGroup(
                    Submit('submit', _('Submit'), css_class='success'),
                    Reset('cancel', _('Cancel')),
                    Button('dummy', _('Delete'), css_class='alert'),
                    css_class='radius right'
                ),
                css_class='clearfix'
            ),
        ),
        Row(
            Column(
                Callout(
                    HTML("""<p>As &lt;input/&gt;</p>"""),
                    ButtonGroup(
                        Submit('submit', _('Submit'), css_class='success'),
                        Reset('cancel', _('Cancel')),
                        Button('dummy', _('Delete'), css_class='alert'),
                        css_class='radius right'
                    ),
                    css_class='clearfix'
                )
            ),
        ),
        Row(
            Column(
                Callout(
                    HTML("""<p>As &lt;button/&gt;</p>"""),
                    ButtonGroup(
                        ButtonSubmit('submit', _('Submit'),
                                     css_class='success'),
                        ButtonReset('cancel', _('Cancel')),
                        ButtonElement('button-label', 'button-value',
                                      css_class='alert',
                                      content="""<span>&lt;Doh/&gt;</span>"""),
                        css_class='radius right'
                    ),
                    css_class='clearfix'
                )
            ),
        ),
    ]
from django import forms
from django.utils.translation import gettext_lazy as _
from crispy_forms.helper import FormHelper
from crispy_forms_foundation.layout import (
    Layout, Fieldset, TabItem, TabHolder, AccordionHolder, AccordionItem
)
from .crispies import (
    part_1_crispies, part_2_crispies, part_3_crispies, part_4_crispies,
    buttons_crispies
)




SELECT_INPUT_CHOICES = [('item-{0}'.format(i), 'Option item {0}'.format(i))
                        for i in range(1, 6)]
RADIO_INPUT_CHOICES = [('item-{0}'.format(i), 'Radio item {0}'.format(i))
                       for i in range(1, 4)]


class BaseForm(forms.Form):
    """
    Base form with inputs
    """
    full_input = forms.CharField(label=_('Full width input'), widget=forms.TextInput(attrs={'required':''}), required=True, help_text="This is a sample field help text.")
    column_input_1 = forms.CharField(label=_('Column input 1'), required=False)
    column_input_2 = forms.CharField(label=_('Column input 2'), required=True)
    column_input_3 = forms.CharField(label=_('Column input 3'), required=False)
    textarea_input = forms.CharField(label=_('Textarea'), widget=forms.Textarea(attrs={'rows':5, 'required':''}), required=True)
    select_input = forms.ChoiceField(label=_('Select input'), choices=SELECT_INPUT_CHOICES, required=True)
    radio_input = forms.ChoiceField(label=_('Radio inputs'), choices=RADIO_INPUT_CHOICES, widget=forms.RadioSelect, required=False)
    checkbox_input = forms.BooleanField(label=_('Checkbox input'), required=False)
    checkbox_switch_input_1 = forms.BooleanField(label=_('Checkbox switch'), required=False)
    checkbox_switch_input_2 = forms.BooleanField(label=_('Checkbox inline switch'), required=False)
    inlinefield_input = forms.CharField(label=_('Inline field'), required=False)
    inlinejustifiedfield_input = forms.CharField(label=_('Inline justified field'), required=False)

    def clean(self):
        cleaned_data = super(BaseForm, self).clean()
        checkbox_input = cleaned_data.get("checkbox_input")

        if checkbox_input and checkbox_input == True:
            raise forms.ValidationError([
                'This is a global error',
                'This is another global error',
                'Uncheck the "Checkbox input" to ignore these errors']
            )

        # Always return the full collection of cleaned data.
        return cleaned_data

    def save(self, commit=True):
        # Do nothing
        return


class FormCrispyHelperMixin(object):
    """
    Form that define an empty helper and able to switch template pack
    """
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.template_pack = kwargs.pop('pack')

        super(FormCrispyHelperMixin, self).__init__(*args, **kwargs)


class FormByFieldsetsForm(FormCrispyHelperMixin, BaseForm):
    def __init__(self, *args, **kwargs):
        super(FormByFieldsetsForm, self).__init__(*args, **kwargs)

        self.helper.attrs = {'data_abide': '', 'novalidate': ''}
        self.helper.form_action = '.'

        part1 = [_('Part 1')]+part_1_crispies(pack=self.helper.template_pack)
        part2 = [_('Part 2')]+part_2_crispies(pack=self.helper.template_pack)
        part3 = [_('Part 3')]+part_3_crispies(pack=self.helper.template_pack)
        part4 = [_('Part 4')]+part_4_crispies(pack=self.helper.template_pack)

        self.helper.layout = Layout(
            Fieldset(*part1),

            Fieldset(*part2),