from django.contrib import admin
from wagtail.models import Page

from vbv_lernwelt.course_session.models import (
    CourseSessionAssignment,
    CourseSessionAttendanceCourse,
    CourseSessionEdoniqTest,
)
from vbv_lernwelt.duedate.models import DueDate
from vbv_lernwelt.learnpath.models import (
    Circle,
    LearningContentAttendanceCourse,
    LearningContentEdoniqTest,
)


@admin.action(description="Re-sync URLs from LearningContent")
def sync_wagtail_due_date_url(modeladmin, request, queryset):
    for assignment in CourseSessionAssignment.objects.all():
        assignment.save()
    for edoniq_test in CourseSessionEdoniqTest.objects.all():
        edoniq_test.save()
    for attendance in CourseSessionAttendanceCourse.objects.all():
        attendance.save()


@admin.register(DueDate)
class DueDateAdmin(admin.ModelAdmin):
    date_hierarchy = "start"
    list_display = [
        "course_session",
        "circle",
        "title",
        "display_subtitle",
        "start",
        "end",
    ]
    list_filter = ["course_session__course", "course_session"]
    readonly_fields = ["course_session", "page"]
    actions = [sync_wagtail_due_date_url]

    def get_readonly_fields(self, request, obj=None):
        default_readonly = super(DueDateAdmin, self).get_readonly_fields(request, obj)

        if obj is None:
            return default_readonly

        if not obj.manual_override_fields:
            return default_readonly + [
                "circle",
                "title",
                "subtitle",
                "assignment_type_translation_key",
                "date_type_translation_key",
                "url",
                "url_expert",
            ]

        return default_readonly

    def circle(self, obj):
        try:
            return obj.page.get_ancestors().exact_type(Circle).first().title
        except Exception:
            # noop
            pass
        return None

    # Create a method that serves as a form field
    def circle_display(self, obj=None):
        if obj:
            return self.circle(obj)
        return None

    circle_display.short_description = "Circle"

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "page":
            if request.resolver_match.kwargs.get("object_id"):
                object_id = int(request.resolver_match.kwargs.get("object_id"))
                csd = DueDate.objects.get(id=object_id)
                kwargs["queryset"] = Page.objects.descendant_of(
                    csd.course_session.course.coursepage
                ).exact_type(LearningContentAttendanceCourse, LearningContentEdoniqTest)
            else:
                kwargs["queryset"] = Page.objects.none()
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
