from django_admin_listfilter_dropdown.filters import RelatedDropdownFilter
from django_object_actions import DjangoObjectActions, takes_instance_or_queryset

from django.contrib import admin
from django.contrib.auth import admin as auth_admin
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group as BaseGroup
from django.utils.translation import gettext_lazy as _

from lms.users.forms import UserChangeForm, UserCreationForm

from .models import Group, PermissionPreset, ServiceAccount, UserForSupport

User = get_user_model()


admin.site.unregister(BaseGroup)
admin.site.site_header = _("LMS")


class BaseUserAdmin(DjangoObjectActions, auth_admin.UserAdmin):
    actions = [
        'flush_available_course_cache_action',
    ]

    change_actions = [
        'flush_available_course_cache_action',
    ]

    @takes_instance_or_queryset
    def flush_available_course_cache_action(self, request, queryset):
        from lms.courses.services import flush_cache_course_available_for, flush_cache_courses_unavailable_for

        users_ids = queryset.only('id').values_list('id', flat=True)
        flush_cache_courses_unavailable_for(users_ids=users_ids)
        flush_cache_course_available_for(users_ids=users_ids)

        self.message_user(
            request=request,
            message=_("Сброс кэша правил видимости выполнен"),
        )

    flush_available_course_cache_action.short_description = _("сбросить кэш правил видимости")
    flush_available_course_cache_action.label = _("сбросить кэш правил видимости")


@admin.register(User)
class UserAdmin(BaseUserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm
    list_display = [
        "username", "email", "yauid", "first_name", "last_name", "is_superuser",
        "date_joined", "last_login",
    ]
    list_filter = (
        'is_staff',
        'is_superuser',
        'is_active',
        ('groups', RelatedDropdownFilter),
    )
    search_fields = ("username", "email", "yauid")

    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        (_('Personal info'), {'fields': ('first_name', 'last_name', 'email')}),
        (_('Yandex'), {'fields': ('yauid',)}),
        (_('Permissions'), {
            'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions'),
        }),
        (_('Important dates'), {'fields': ('last_login', 'date_joined')}),
    )


@admin.register(UserForSupport)
class ForSupportUserAdmin(BaseUserAdmin):
    list_display = [
        'username',
    ]
    search_fields = ('username',)
    fieldsets = (
        (None, {'fields': ('username',)}),
    )


@admin.register(Group)
class GroupAdmin(auth_admin.GroupAdmin):
    pass


@admin.register(PermissionPreset)
class PermissionPresetAdmin(admin.ModelAdmin):
    filter_horizontal = ('permissions',)


@admin.register(ServiceAccount)
class ServiceAccountAdmin(admin.ModelAdmin):
    list_display = [
        'tvm_id', 'name', 'description', 'is_active', 'created', 'modified'
    ]
    search_fields = ('id', 'tvm_id', 'name')
    list_filter = ('is_active',)
