from django.contrib import admin

from vbv_lernwelt.course.models import Course, CourseSession, CourseSessionUser
from vbv_lernwelt.learnpath.models import Circle


@admin.register(Course)
class CourseAdmin(admin.ModelAdmin):
    list_display = [
        "id",
        "title",
        "category_name",
        "slug",
    ]


@admin.register(CourseSession)
class CourseSessionAdmin(admin.ModelAdmin):
    date_hierarchy = "created_at"
    list_display = [
        "title",
        "course",
        "import_id",
        "start_date",
        "end_date",
        "created_at",
        "updated_at",
    ]


@admin.register(CourseSessionUser)
class CourseSessionUserAdmin(admin.ModelAdmin):
    date_hierarchy = "created_at"
    list_display = [
        "user",
        "course_session",
        "role",
        "created_at",
        "updated_at",
    ]
    search_fields = [
        "user__first_name",
        "user__last_name",
        "user__email",
        "course_session__title",
    ]
    list_filter = [
        "course_session",
        "role",
    ]
    raw_id_fields = [
        "user",
    ]

    fieldsets = [
        (None, {"fields": ("user", "course_session", "role")}),
        (
            "Expert/Trainer",
            {
                "fields": ("expert",),
                "description": "Expert/Trainer kann erst ausgewählt werden, wenn der Kurs ausgewählt und bereits einmal gespeichert wurde.",
            },
        ),
    ]

    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "expert":
            if request.resolver_match.kwargs.get("object_id"):
                object_id = int(request.resolver_match.kwargs.get("object_id"))
                csu = CourseSessionUser.objects.get(id=object_id)
                kwargs["queryset"] = Circle.objects.descendant_of(
                    csu.course_session.course.coursepage
                )
            else:
                kwargs["queryset"] = Circle.objects.none()
        return super().formfield_for_manytomany(db_field, request, **kwargs)
