"""
Created on 19.09.2011

@author: christian
"""
# import stuff we need from django
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.utils.translation import ugettext as _
from imagekit.admin import AdminThumbnail

from membership.models import Membership, ActivationRequest


def activate_user(modeladmin, request, queryset):
    for activation in queryset:
        membership = Membership.objects.get(username=activation.user.username)
        membership.save()
        activation.activate()


activate_user.short_description = _('Activate selected User')


def cleanup_activation(modeladmin, request, queryset):
    for activation in queryset:
        if activation.expired:
            activation.user.delete()


cleanup_activation.short_description = _("Cleanup selected Activation Requests")


class ProxyGroup(Group):
    class Meta:
        proxy = True
        verbose_name = _('Group')
        verbose_name_plural = _('Groups')


class MembershipAdmin(UserAdmin):
    admin_thumbnail = AdminThumbnail(image_field='thumbnail')
    list_filter = ('membership', 'confirmed')
    list_display = (
        'admin_thumbnail',
        'username',
        'first_name',
        'last_name',
        'membership',
        'confirmed',
        'paid_until',
    )
    list_editable = ('confirmed', 'paid_until',)
    list_display_links = ('username',)
    fieldsets = (
        (None, {'fields': (('username', 'password'), 'gender',
                           ('first_name', 'last_name'), ('email', 'website'))}),
        (_('Membership'), {'classes': ('collapse',),
                           'fields': (('membership', 'confirmed'), 'birthday', 'telephone',
                                       'street_name', ('post_code', 'city'))}),
        (_('Permissions'), {'fields': ('is_active', 'is_staff', 'is_superuser',
                                       'groups', 'user_permissions')}),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )
    ordering = ('username',)
    search_fields = ('username', 'first_name', 'last_name',)


admin.site.register(Membership, MembershipAdmin)


class RegistrationAdmin(admin.ModelAdmin):
    list_display = ('username', 'first_name', 'last_name', 'email',
                    'registration_date', 'expired')
    search_fields = ('user__username', 'user__first_name')
    actions = [cleanup_activation, activate_user]


admin.site.register(ActivationRequest, RegistrationAdmin)
admin.site.unregister(Group)
admin.site.register(ProxyGroup, GroupAdmin)
