"""This module holds the forms for the ``workshops`` app"""

from django import forms
from django.utils.translation import ugettext_lazy as _

from mtp.apps.assessments.forms import AssessableMixin
from mtp.apps.common.widgets import FarbtasticColorPicker

from .constants import ANSWER_TITLE_MAX_LENGTH, QUESTION_TITLE_MAX_LENGTH
from .models import (
    WorkshopStepQuestion,
    WorkshopStepQuestionAnswer,
)


class WorkshopStepQuestionForm(AssessableMixin, forms.ModelForm):

    class Meta:
        model = WorkshopStepQuestion
        fields = (
            'title',
            'is_multiple_choices',
            'is_all_or_nothing',
            'is_answers_order_random',
            'is_assessing',
            'dimensions',
        )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Hack: apply a maximal length limit to fit the iOS display.
        self.fields['title'].widget.attrs['maxlength'] = QUESTION_TITLE_MAX_LENGTH
        self.fields['title'].help_text = _(
            "Field length limited to %d characters." % QUESTION_TITLE_MAX_LENGTH
        )

    def clean(self):
        """Check that the `is_multiple_choices` is enable to activate `is_all_or_nothing` option."""
        cleaned_data = super().clean()
        if cleaned_data['is_all_or_nothing'] and not cleaned_data['is_multiple_choices']:
            self.add_error('is_all_or_nothing', _("You must activate 'is_multiple_choices' option "
                                                  "to enable it."))


class WorkshopStepQuestionAnswerForm(forms.ModelForm):
    class Meta:
        model = WorkshopStepQuestionAnswer
        fields = (
            'label', 'color', 'is_correct', 'points',
        )
        widgets = {'color': FarbtasticColorPicker}

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # Limitation of characters for displaying correctly label in iOS without modify database
        self.fields['label'].widget.attrs['maxlength'] = ANSWER_TITLE_MAX_LENGTH
        self.fields['label'].help_text = "Field limited to %d characters." % ANSWER_TITLE_MAX_LENGTH
