from django import forms
from django.contrib.auth.models import Group, User

from .fields import KFetPermissionsField


class GroupForm(forms.ModelForm):
    permissions = KFetPermissionsField()

    def clean_name(self):
        name = self.cleaned_data["name"]
        return "K-Fêt %s" % name

    def clean_permissions(self):
        kfet_perms = self.cleaned_data["permissions"]
        # TODO: With Django >=1.11, the QuerySet method 'difference' can be
        # used.
        # other_groups = self.instance.permissions.difference(
        #     self.fields['permissions'].queryset
        # )
        if self.instance.pk is None:
            return kfet_perms
        other_perms = self.instance.permissions.exclude(
            pk__in=[p.pk for p in self.fields["permissions"].queryset]
        )
        return list(kfet_perms) + list(other_perms)

    class Meta:
        model = Group
        fields = ["name", "permissions"]


class UserGroupForm(forms.ModelForm):
    groups = forms.ModelMultipleChoiceField(
        Group.objects.filter(name__icontains="K-Fêt"),
        label="Statut équipe",
        required=False,
    )

    def clean_groups(self):
        kfet_groups = self.cleaned_data.get("groups")
        if self.instance.pk is None:
            return kfet_groups
        other_groups = self.instance.groups.exclude(name__icontains="K-Fêt")
        return list(kfet_groups) + list(other_groups)

    class Meta:
        model = User
        fields = ["groups"]
