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

from objectives.models import ObjectiveGroup, Objective
from books.models import Topic


@admin.register(ObjectiveGroup)
class ObjectiveGroupAdmin(admin.ModelAdmin):
    list_display = ('title', 'module')
    list_filter = ('title', 'module')


@admin.register(Objective)
class ObjectiveAdmin(admin.ModelAdmin):
    list_display = ('text', 'get_topic', 'group', 'order', 'owner')
    list_filter = ('group', 'owner')

    def get_topic(self, obj):
        try:
            page = Page.objects.get(pk=obj.group.module.page_ptr_id)
        except Page.DoesNotExist:
            return None

        parent_path = str(page.path)[:-4]

        try:
            parent = Page.objects.get(path=parent_path)
        except Page.DoesNotExist:
            return None

        try:
            topic = Topic.objects.get(page_ptr_id=parent.id)
        except Topic.DoesNotExist:
            return None

        return topic.title

    get_topic.short_description = 'Thema'
