from django.contrib import admin
from django import forms
from .models import ScheduledTask
from django.templatetags.static import static
from scheduler.utils import get_project_functions


class ScheduledTaskForm(forms.ModelForm):
    """
    Форма для модели ScheduledTask с кастомным полем для выбора дней недели.
    """
    DAYS_OF_WEEK_CHOICES = [
        (0, "Воскресенье"),
        (1, "Понедельник"),
        (2, "Вторник"),
        (3, "Среда"),
        (4, "Четверг"),
        (5, "Пятница"),
        (6, "Суббота"),
    ]

    weekdays = forms.MultipleChoiceField(
        choices=DAYS_OF_WEEK_CHOICES,
        widget=forms.CheckboxSelectMultiple,
        label="Дни недели",
        required=False,
    )

    class Meta:
        model = ScheduledTask
        fields = [
            "task_name",
            "function_path",
            "minutes",
            "hours",
            "months",
            "weekdays",
            "active",
        ]

    def clean_weekdays(self):
        """
        Преобразует список выбранных дней в строку для сохранения в базе.
        """
        weekdays = self.cleaned_data.get("weekdays", [])
        return ",".join(map(str, weekdays))


@admin.register(ScheduledTask)
class ScheduledTaskAdmin(admin.ModelAdmin):
    """
    Кастомный класс для управления ScheduledTask в админке.
    """
    form = ScheduledTaskForm
    list_display = ("task_name", "function_path", "minutes", "hours", "months", "weekdays", "active", "formatted_last_run")
    list_filter = ("active",)
    search_fields = ("task_name", "function_path")

    def formatted_last_run(self, obj):
        """
        Отформатированный вывод времени последнего запуска задачи.
        """
        return obj.last_run.strftime("%Y-%m-%d %H:%M:%S") if obj.last_run else "Никогда"

    formatted_last_run.short_description = "Последний запуск"
