from django.db import models
from django.utils.timezone import now


class ScheduledTask(models.Model):
    task_name = models.CharField(max_length=255)
    function_path = models.CharField(max_length=255)
    minutes = models.CharField(max_length=255)
    hours = models.CharField(max_length=255)
    months = models.CharField(max_length=255)
    weekdays = models.CharField(max_length=100, blank=True, default="")
    active = models.BooleanField(default=True)
    last_run = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return self.name

    def clean_weekdays(self):
        """Приводим список в строку при сохранении."""
        if isinstance(self.weekdays, list):
            self.weekdays = ",".join(map(str, self.weekdays))
            
    class Meta:
        verbose_name = "Запланированная задача"
        verbose_name_plural = "Запланированные задачи"

def get_available_functions():
    from scheduler.utils import get_project_functions
    return [(path, name) for path, name in get_project_functions()]

class ScheduledTask(models.Model):
    task_name = models.CharField(max_length=255, verbose_name="Название задачи")
    function_path = models.CharField(
        max_length=500,
        choices=get_available_functions,
        verbose_name="Путь к функции (модуль.функция)",
    )
    minutes = models.CharField(max_length=255, verbose_name="Минуты", default="*")
    hours = models.CharField(max_length=255, verbose_name="Часы", default="*")
    days = models.CharField(max_length=255, verbose_name="Дни", default="*")
    months = models.CharField(max_length=255, verbose_name="Месяцы", default="*")
    weekdays = models.JSONField(default=list, verbose_name="Дни недели")
    active = models.BooleanField(default=True, verbose_name="Активно")
    last_run = models.DateTimeField(blank=True, null=True, verbose_name="Последний запуск")

    def __str__(self):
        return self.task_name