"""Contains form class defintions for form for the questions app.

Classes: [
    SurveyQuestionForm
]
"""

from django import forms
from django.core.urlresolvers import reverse

from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout

from . import config
from .models import ChoiceSelectionAnswerFormat, ListInputAnswerFormat


class SurveyQuestionForm(forms.Form):
    """Models a form for how a question should be posed to the user."""

    answer_input = forms.CharField(
        label = "",
        required=False,
        widget=forms.Textarea()
    )

    class Meta:
        fields = ("answer_input")

    def __init__(self, *args, **kwargs):
        survey_question = kwargs.pop('survey_question', None)

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

        # NOTE: It is assumed that all answer_formats belonging to a question
        # is of the same type.
        # TODO: ENHANCEMENT: Enforce same answer format instances or throw an
        # error
        answer_formats = survey_question.question.answer_formats.all()
        answer_format = answer_formats[0]

        # Determine what the type of 'answer_input' form field is and its
        # associated widget type.
        if isinstance(answer_format, ChoiceSelectionAnswerFormat):
            choices = ((a.id, a.choice_name) for a in answer_formats)
            label = ""
            required = False

            if (answer_format.answer_format_type == config.CHOICE_SELECTION_MANY_FORMAT):

                self.fields['answer_input'] = forms.MultipleChoiceField(
                    label=label,
                    required=required,
                    choices=choices
                )
                self.fields['answer_input'].widget = forms.CheckboxSelectMultiple()
            else:
                self.fields['answer_input'] = forms.ChoiceField(
                    label=label,
                    required=required,
                    choices=choices
                )

                self.fields['answer_input'].widget = forms.RadioSelect()
        elif isinstance(answer_format, ListInputAnswerFormat):
            self.fields['answer_input'].help_text = "Please enter each new item on a new line."

        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.form_method = 'post'
        self.helper.form_action = reverse("questions:answer-survey-question")
        self.helper.layout = Layout(
            'answer_input',
        )
        self.helper.layout.append(
            FormActions(
                Submit('skip', 'Skip'),
                Submit('submit', 'Submit', css_class='btn-primary'),
            )
        )
