from django.contrib import admin
from django.utils.translation import gettext_lazy as _

from aircox.models import Program, Schedule, Stream
from .page import PageAdmin
from .schedule import ScheduleInline


__all__ = ("ProgramAdmin", "StreamInline", "StreamAdmin")


class StreamInline(admin.TabularInline):
    model = Stream
    fields = ["delay", "begin", "end"]
    extra = 1


@admin.register(Program)
class ProgramAdmin(PageAdmin):
    def schedule(self, obj):
        return Schedule.objects.filter(program=obj).count() > 0

    schedule.boolean = True
    schedule.short_description = _("Schedule")

    list_display = PageAdmin.list_display + ("schedule", "station", "active")
    list_filter = PageAdmin.list_filter + ("station", "active")
    prepopulated_fields = {"slug": ("title",)}
    search_fields = ("title",)

    inlines = [ScheduleInline, StreamInline]

    def get_fieldsets(self, request, obj=None):
        fields = super().get_fieldsets(request, obj)
        if request.user.has_perm("aircox.program.scheduling"):
            fields = fields + [
                (
                    _("Program Settings"),
                    {
                        "fields": ["active", "station", "sync"],
                    },
                )
            ]
        return fields


@admin.register(Stream)
class StreamAdmin(admin.ModelAdmin):
    list_display = ("id", "program", "delay", "begin", "end")
