""" Admin Interface to manage the memberships."""
# import stuff we need from django
from django.contrib import admin, messages
from django.contrib.auth.admin import UserAdmin, GroupAdmin
from django.contrib.auth.models import Group
from django.core.exceptions import PermissionDenied
from django.utils.translation import gettext as _
from easy_thumbnails import fields, widgets
from membership.models import Membership, ActivationRequest


def activate_user(modeladmin, request, queryset):
    """Triggers activation of the selects actication requests by hand.

    :param modeladmin: The ModelAdmin that triggered this action.
    :param request: An HttpRequest representing the current request.
    :param queryset: A QuerySet containing the objects selected by the user.
    """
    [activation.activate() for activation in queryset]


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


def cleanup_activation(modeladmin, request,
                       queryset):  # Ignore PyLintBear (W0613)
    """Delete every selected activation request that has been expired.

    :param modeladmin: The ModelAdmin that triggered this action.
    :param request: An HttpRequest representing the current request.
    :param queryset: A QuerySet containing the objects selected by the user.
    """
    for activation in queryset:
        if activation.expired:
            activation.user.delete()


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


def clear_personal_data(modeladmin, request, queryset):
    """deactivates the account and removes all personal user information.

    :param modeladmin: The ModelAdmin that triggered this action.
    :param request: An HttpRequest representing the current request.
    :param queryset: A QuerySet containing the objects selected by the user.
    """
    cleared_memberships = 0
    if not modeladmin.has_delete_permission(request):
        raise PermissionDenied
    for membership in queryset:
        if membership.membership == False:
            [setattr(membership, fieldname, None)
             for fieldname in membership.nullable_personal_data]
            [setattr(membership, fieldname, "")
             for fieldname in membership.blankable_personal_data]
            membership.is_active = False
            membership.confirmed = False
            membership.membership = False
            membership.save()
            cleared_memberships += 1
        else:
            modeladmin.message_user(request, _(
                "Can't remove personal data from active member %s.") % membership.username, messages.ERROR)
    if cleared_memberships > 0:
        modeladmin.message_user(request, _(
            "Cleared %d personal data profiles.") % cleared_memberships, messages.INFO)


clear_personal_data.short_description = _("Clear personal Data")


class ProxyGroup(Group):
    """A Proxy to list Usergroups from django.contrib.auth here."""

    class Meta:
        """ MetaData to localize this Proxy Group."""
        proxy = True
        verbose_name = _('Group')
        verbose_name_plural = _('Groups')


class MembershipAdmin(UserAdmin):
    """Admin interface to manage membership. e.g. users."""
    actions = [clear_personal_data, ]

    formfield_overrides = {
        fields.ThumbnailerImageField: {
            'widget': widgets.ImageClearableFileInput},
    }
    list_filter = ('is_active', 'membership', 'confirmed')
    list_display = (
        'username',
        'first_name',
        'last_name',
        'is_active',
        'membership',
        'confirmed',
        'last_login',
    )
    list_editable = ('confirmed', )
    list_display_links = ('username',)
    fieldsets = (
        (None, {'fields': (('username', 'password'), 'gender', 'avatar',
                           ('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):
    """To administrag user activation requests.
    Kasu uses an two factor registration via email."""
    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)
