# Generated by Django 3.2.12 on 2022-04-02 00:41

from django.db import migrations
from django.utils.timezone import make_aware

from tacticalrmm.constants import TaskType


def migrate_script_data(apps, schema_editor):
    AutomatedTask = apps.get_model("autotasks", "AutomatedTask")
    # convert autotask to the new format
    for task in AutomatedTask.objects.all():
        try:
            edited = False

            # convert scheduled task_type
            if task.task_type == TaskType.SCHEDULED:
                task.task_type = TaskType.DAILY
                task.run_time_date = make_aware(task.run_time_minute.strptime("%H:%M"))
                task.daily_interval = 1
                edited = True

            # convert actions
            if not task.actions:
                if not task.script:
                    task.delete()

                task.actions = [
                    {
                        "type": "script",
                        "script": task.script.pk,
                        "script_args": task.script_args,
                        "timeout": task.timeout,
                        "name": task.script.name,
                    }
                ]
                edited = True

            if edited:
                task.save()
        except:
            continue


class Migration(migrations.Migration):

    dependencies = [
        ("autotasks", "0032_auto_20220401_2301"),
    ]

    operations = [
        migrations.RunPython(migrate_script_data),
    ]
