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

from aircox.models import Episode, EpisodeSound
from .page import ChildPageAdmin
from .sound import TrackInline
from .diffusion import DiffusionInline


class EpisodeSoundInline(admin.TabularInline):
    model = EpisodeSound
    extra = 0
    fields = (
        "sound",
        "position",
        "broadcast",
    )
    autocomplete_fields = ("sound",)


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


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

    inlines = (TrackInline, EpisodeSoundInline, DiffusionInline)
    ordering = ["-pub_date"]
