from adminsortable2.admin import SortableAdminBase
from django.contrib import admin
from django.forms import ModelForm

from aircox.models import Episode
from .page import PageAdmin
from .sound import SoundInline, TrackInline
from .diffusion import DiffusionInline


class EpisodeAdminForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields["parent"].required = True


@admin.register(Episode)
class EpisodeAdmin(SortableAdminBase, PageAdmin):
    form = EpisodeAdminForm
    list_display = PageAdmin.list_display
    list_filter = tuple(
        f for f in PageAdmin.list_filter if f != "pub_date"
    ) + (
        "diffusion__start",
        "pub_date",
    )
    search_fields = PageAdmin.search_fields + ("parent__title",)
    # readonly_fields = ('parent',)

    inlines = [TrackInline, SoundInline, DiffusionInline]

    def add_view(self, request, object_id, form_url="", context=None):
        context = context or {}
        context["init_app"] = True
        context["init_el"] = "#inline-tracks"
        return super().change_view(request, object_id, form_url, context)

    def change_view(self, request, object_id, form_url="", context=None):
        context = context or {}
        context["init_app"] = True
        context["init_el"] = "#inline-tracks"
        return super().change_view(request, object_id, form_url, context)
