from django import forms
from django.utils.datastructures import MultiValueDict

from . labels import get_label_choices
from . models import (
    BinaryQuestion,
    BinaryResponse,
    LikertQuestion,
    LikertResponse,
    MultipleChoiceQuestion,
    MultipleChoiceResponse,
    OpenEndedQuestion,
    OpenEndedResponse,
    SurveyResult
)


class ArrayFieldSelectMultiple(forms.SelectMultiple):
    """This is a Form Widget for use with a Postgres ArrayField. It implements
    a multi-select interface that can be given a set of `choices`.

    You can provide a `delimiter` keyword argument to specify the delimeter used.

    """

    def __init__(self, *args, **kwargs):
        self.delimiter = kwargs.pop("delimiter", ",")
        super(ArrayFieldSelectMultiple, self).__init__(*args, **kwargs)

    def render_options(self, choices, value):
        # Value *should* be a list, but it might be a delimited string.
        if isinstance(value, str):
            value = value.split(self.delimiter)
        return super(ArrayFieldSelectMultiple, self).render_options(choices, value)

    def value_from_datadict(self, data, files, name):
        if isinstance(data, MultiValueDict):
            # Normally, we'd want a list here, but the SimpleArrayField
            # expects to get a string
            return self.delimiter.join(data.getlist(name))
        return data.get(name, None)


class BaseQuestionForm(forms.ModelForm):
    """A Base form for all question types. This Form includes the widgets and
    Media definitions for labels (ArrayFields).

    """

    class Meta:
        widgets = {
            "labels": ArrayFieldSelectMultiple(
                choices=get_label_choices(), attrs={'class': 'chosen'}),
        }

    class Media:
        css = {
            "all": ("js/chosen/chosen.min.css", )
        }
        js = ("js/chosen/chosen.jquery.min.js", )