from django_celery_beat.models import PeriodicTask

from core.utils import dtnow, fmt_input
from rotation.constants import ROTATE_SIZE_CHECK_CRONTAB
from rotation.enums import RotationType
from rotation.services.cron_utils import serializer_to_model, crontab_to_schedule


def update_model_with_data(serializer, settings_class, type, task_name):
    schedule = None
    if serializer.validated_data['rotation_type'] == RotationType.TIME:
        schedule = serializer_to_model(serializer)
    elif serializer.validated_data['rotation_type'] == RotationType.SIZE:
        schedule = crontab_to_schedule(ROTATE_SIZE_CHECK_CRONTAB)
    elif serializer.validated_data['rotation_type'] == RotationType.DISABLED:
        # If user disable rotation
        settings = disable_rotation(settings_class)
        return settings

    schedule.save()

    settings = settings_class.get_solo()
    settings.rotation_type = serializer.validated_data['rotation_type']
    if not settings.task:
        settings.task = PeriodicTask(name=f'Journal {type} rotation {fmt_input(dtnow())}',
                                     task=task_name,
                                     enabled=True,
                                     crontab=schedule,
                                     start_time=dtnow())
        settings.task.save()
    else:
        old = settings.task.crontab
        settings.task.crontab = schedule
        settings.task.save()
        old.delete()

    if settings.rotation_type == RotationType.SIZE:
        settings.size_rotation = serializer.validated_data['size_rotation']

    settings.save()
    return settings


def disable_rotation(settings_class):
    settings = settings_class.get_solo()
    settings.rotation_type = RotationType.DISABLED
    if settings.task:
        if settings.task.crontab:
            settings.task.crontab.delete()
        settings.task.delete()
        settings.task = None
    settings.save()
    return settings
