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

from aircox.models import Diffusion


__all__ = ("DiffusionBaseAdmin", "DiffusionAdmin", "DiffusionInline")


class DiffusionBaseAdmin:
    fields = ("type", "start", "end", "schedule")
    readonly_fields = ("schedule",)

    def get_readonly_fields(self, request, obj=None):
        fields = super().get_readonly_fields(request, obj)
        if not request.user.has_perm("aircox_program.scheduling"):
            fields = fields + ("program", "start", "end")
        return [field for field in fields if field in self.fields]


@admin.register(Diffusion)
class DiffusionAdmin(DiffusionBaseAdmin, admin.ModelAdmin):
    def start_date(self, obj):
        return obj.local_start.strftime("%Y/%m/%d %H:%M")

    start_date.short_description = _("start")

    def end_date(self, obj):
        return obj.local_end.strftime("%H:%M")

    end_date.short_description = _("end")

    list_display = ("episode", "start_date", "end_date", "type", "initial")
    list_filter = ("type", "start", "program")
    list_editable = ("type",)
    ordering = ("-start", "id")

    fields = ("type", "start", "end", "initial", "program", "schedule")
    readonly_fields = ("schedule",)


class DiffusionInline(DiffusionBaseAdmin, admin.TabularInline):
    model = Diffusion
    fk_name = "episode"
    extra = 0

    def has_add_permission(self, request, obj):
        return request.user.has_perm("aircox_program.scheduling")
