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

#
# In the models listed below standard permissions "add_model", "change_model"
# and "delete_model" will be created by syncdb, but hidden from admin interface.
# This is convenient in case you use your own set of permissions so the list
# in the admin interface wont be confusing.
# Feel free to add your models here. The first element is the app name (this is
# the directory your app is in) and the second element is the name of your model
# from models.py module of your app (Note: both names must be lowercased).
#
MODELS_TO_HIDE_STD_PERMISSIONS = (
    ("abstracts", "AbstractRequest"),
)

def _get_corrected_permissions():
    perms = Permission.objects.all()
    for app_name, model_name in MODELS_TO_HIDE_STD_PERMISSIONS:
        perms = perms.exclude(codename__startswith='add_')
        perms = perms.exclude(codename__startswith='change_')
        perms = perms.exclude(codename__startswith='delete_')
    return perms

class MyGroupAdminForm(forms.ModelForm):

    class Meta:
        model = Group
        fields = ('__all__')

    permissions = forms.ModelMultipleChoiceField(
        _get_corrected_permissions(),
        widget=admin.widgets.FilteredSelectMultiple(('permissions'), False),
        help_text = 'Hold down "Control", or "Command" on a Mac, to select more than one.'
    )

class MyGroupAdmin(GroupAdmin):

    form = MyGroupAdminForm

class MyUserChangeForm(UserChangeForm):

    user_permissions = forms.ModelMultipleChoiceField(
        _get_corrected_permissions(),
        widget=admin.widgets.FilteredSelectMultiple(('user_permissions'), False),
        help_text = 'Hold down "Control", or "Command" on a Mac, to select more than one.'
    )

class MyUserAdmin(UserAdmin):

    form = MyUserChangeForm

admin.site.unregister(Group)
admin.site.register(Group, MyGroupAdmin)
admin.site.unregister(User)
admin.site.register(User,MyUserAdmin)
