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

from aircox.models import Schedule


__all__ = ("ScheduleInlineForm", "ScheduleInline", "ScheduleAdmin")


# In order to simplify schedule_post_save algorithm, an existing schedule can't
# update the following fields: "frequency", "date"
class ScheduleInlineForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.initial:
            self.fields["date"].disabled = True
            self.fields["frequency"].disabled = True


class ScheduleInline(admin.TabularInline):
    model = Schedule
    form = ScheduleInlineForm
    readonly_fields = ("timezone",)
    extra = 1


@admin.register(Schedule)
class ScheduleAdmin(admin.ModelAdmin):
    def program_title(self, obj):
        return obj.program.title

    program_title.short_description = _("Program")

    def freq(self, obj):
        return obj.get_frequency_display()

    freq.short_description = _("Day")

    list_filter = ["frequency", "program"]
    list_display = [
        "program_title",
        "freq",
        "time",
        "timezone",
        "duration",
        "initial",
    ]
    list_editable = ["time", "duration", "initial"]

    def get_readonly_fields(self, request, obj=None):
        if obj:
            return ["program", "date", "frequency"]
        else:
            return []
