from django import forms
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.models import User, Group, Permission

from djangotoolbox.auth.utils import update_permissions_user, update_user_groups
from djangotoolbox.auth.models import UserPermissionList, GroupList


class UserForm(forms.ModelForm):
    permissions = forms.MultipleChoiceField(required=False)
    groups = forms.MultipleChoiceField(required=False)
    
    def __init__(self, *args, **kwargs):
        super(UserForm, self).__init__(*args, **kwargs)
   
        permissions_objs = Permission.objects.all().order_by('name')
        choices = list ()
        for perm_obj in permissions_objs:
            choices.append([perm_obj.id, perm_obj.name])
        self.fields['permissions'].choices = choices
        
        group_objs = Group.objects.all()
        choices = list ()
        for group_obj in group_objs:
            choices.append([group_obj.id, group_obj.name])
        self.fields['groups'].choices = choices


        try:
            user_perm_list = UserPermissionList.objects.get(user=kwargs['instance'])
            self.fields['permissions'].initial = user_perm_list.fk_list
        except UserPermissionList.DoesNotExist:
            pass

        try:
            user_group_list = GroupList.objects.get(user=kwargs['instance'])
            self.fields['groups'].initial = user_group_list.fk_list
        except GroupList.DoesNotExist:
            pass
                                    
        
        
    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name', 'is_active',
                  'is_staff', 'is_superuser',)


class CustomUserAdmin(UserAdmin):
    fieldsets = None
    form = UserForm
    
    def save_model(self, request, obj, form, change):
        super(CustomUserAdmin, self).save_model(request, obj, form, change)

        if len(form.cleaned_data['permissions']) > 0:
            permissions = list(Permission.objects.filter(id__in=form.cleaned_data['permissions']).order_by('name'))
        else:
            permissions = list()
            

        update_permissions_user(permissions, obj)

        if len(form.cleaned_data['groups']) > 0:
            groups = list(Group.objects.filter(id__in=form.cleaned_data['groups']))
        else:
            groups = list()

        update_user_groups(obj, groups)
                
class PermissionAdmin(admin.ModelAdmin):
    ordering = ('name',)


class GroupForm(forms.ModelForm):
    class Meta:
        model = Group
        fields = ('name',)
        
class CustomGroupAdmin(admin.ModelAdmin):
    form = GroupForm
    fieldsets = None

admin.site.unregister(User)
admin.site.unregister(Group)
admin.site.register(Group, CustomGroupAdmin)
admin.site.register(User, CustomUserAdmin)
admin.site.register(Permission, PermissionAdmin)

@@ -255,16 +255,42 @@
 r_groups
+, update_permissions_group
 %0Afrom dj
@@ -349,16 +349,37 @@
 roupList
+, GroupPermissionList
 %0A%0A%0Aclass
@@ -2590,24 +2590,691 @@
 ModelForm):%0A
+    permissions = forms.MultipleChoiceField(required=False)%0A    %0A    def __init__(self, *args, **kwargs):%0A        super(GroupForm, self).__init__(*args, **kwargs)%0A   %0A        permissions_objs = Permission.objects.all().order_by('name')%0A        choices = list ()%0A        for perm_obj in permissions_objs:%0A            choices.append(%5Bperm_obj.id, perm_obj.name%5D)%0A        self.fields%5B'permissions'%5D.choices = choices%0A%0A        try:%0A            current_perm_list = GroupPermissionList.objects.get(group=kwargs%5B'instance'%5D)%0A            self.fields%5B'permissions'%5D.initial = current_perm_list.fk_list%0A        except UserPermissionList.DoesNotExist:%0A            pass%0A        %0A
     class Me
@@ -3269,32 +3269,32 @@
     class Meta:%0A
-
         model = 
@@ -3326,25 +3326,17 @@
 name',)%0A
-        
 %0A
+
 class Cu
@@ -3386,24 +3386,24 @@
 = GroupForm%0A
-
     fieldset
@@ -3412,16 +3412,431 @@
 = None%0A%0A
+    def save_model(self, request, obj, form, change):%0A        super(CustomGroupAdmin, self).save_model(request, obj, form, change)%0A%0A        if len(form.cleaned_data%5B'permissions'%5D) %3E 0:%0A            permissions = list(Permission.objects.filter(id__in=form.cleaned_data%5B'permissions'%5D).order_by('name'))%0A        else:%0A            permissions = list()%0A            %0A%0A        update_permissions_group(permissions, obj)%0A%0A
 admin.si

add permission field to GroupForm