'''
ChoiceGroup & Choice managing views
'''

from django import forms
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _
from django.views.generic import UpdateView
from django.views.generic.edit import ModelFormMixin

from ngw.core import perms
from ngw.core.models import ChoiceGroup, ContactField
from ngw.core.views.generic import InGroupAcl

#######################################################################
#
# Choice groups edit / add
#
#######################################################################


class ChoicesWidget(forms.MultiWidget):
    def __init__(self, ndisplay, attrs=None):
        widgets = []
        attrs_value = attrs or {}
        attrs_key = attrs or {}
        attrs_value['style'] = 'width:85%'
        attrs_key['style'] = 'width:7%; margin-left:1ex;'

        for i in range(ndisplay):
            widgets.append(forms.TextInput(attrs=attrs_value))
            widgets.append(forms.TextInput(attrs=attrs_key))
        super().__init__(widgets, attrs)
        self.ndisplay = ndisplay

    def decompress(self, value):
        if value:
            return value.split('\u001f')
        nonelist = []
        for i in range(self.ndisplay):
            nonelist.append(None)
        return nonelist


class ChoicesField(forms.MultiValueField):
    def __init__(self, ndisplay, *args, **kwargs):
        fields = []
        for i in range(ndisplay):
            fields.append(forms.CharField())
            fields.append(forms.CharField())
        super().__init__(fields, *args, **kwargs)
        self.ndisplay = ndisplay

    def compress(self, data_list):
        if data_list:
            return '\u001f'.join(data_list)
        return None

    def clean(self, value):
        keys = []
        raw_values = forms.MultiValueField.clean(self, value)
        if raw_values:
            possibles_values = raw_values.split('\u001f')
        else:
            possibles_values = []
        # print('possibles_values=', repr(possibles_values))
        # check there is no duplicate keys
        # necessary since keys are the id used in <select>
        for i in range(len(possibles_values)//2):
            v, k = possibles_values[2*i], possibles_values[2*i+1]
            if not v:
                continue  # ignore lines without values
            if not k:
                continue  # empty keys are ok
            if k in keys:
                raise forms.ValidationError(_(
                    'You cannot have two keys with the same value. Leave empty'
                    ' for automatic generation.'))
            keys.append(k)
        return possibles_values


class ChoiceGroupForm(forms.ModelForm):
    class Meta:
        model = ChoiceGroup
        fields = ['sort_by_key']

    def __init__(self, *args, **kwargs):
        choicegroup = kwargs.get('instance', None)
        super().__init__(*args, **kwargs)