# Generated by Django 4.0.3 on 2022-04-15 18:18

from django.db import migrations
from django.db.models import Count

from autotasks.models import generate_task_name
from tacticalrmm.constants import TaskSyncStatus


def check_for_win_task_name_duplicates(apps, schema_editor):
    AutomatedTask = apps.get_model("autotasks", "AutomatedTask")
    TaskResult = apps.get_model("autotasks", "TaskResult")

    duplicate_tasks = (
        AutomatedTask.objects.values("win_task_name")
        .annotate(records=Count("win_task_name"))
        .filter(records__gt=1)
    )
    for task in duplicate_tasks:
        dups = list(AutomatedTask.objects.filter(win_task_name=task["win_task_name"]))
        for x in range(task["records"] - 1):

            dups[x].win_task_name = generate_task_name()
            dups[x].save(update_fields=["win_task_name"])
            # update task_result sync status
            TaskResult.objects.filter(task=dups[x]).update(
                sync_status=TaskSyncStatus.NOT_SYNCED
            )


class Migration(migrations.Migration):

    dependencies = [
        ("autotasks", "0034_auto_20220402_0046"),
    ]

    operations = [
        migrations.RunPython(check_for_win_task_name_duplicates),
    ]
