# Generated by Django 2.0.4 on 2018-05-30 12:19

from django.db import migrations


def add_task_name(apps, schema_editor):
    """
    This function loops through all ScheduledTask objects and sets the task_name to a unique value, based on the
    existing task attribute, e.g.
    myapp.mytasks.hello-world
    myapp.mytasks.hello-world-1
    myapp.mytasks.hello-world-2
    """
    ScheduledTask = apps.get_model("carrot", "ScheduledTask")
    db_alias = schema_editor.connection.alias

    for index, t in ScheduledTask.objects.using(db_alias):
        task_name = t.task
        others = ScheduledTask.objects.using(db_alias).filter(task=task_name).exclude(pk=t.pk)
        if others:
            task_name = '%s-%i' % (task_name, index + 1)
        t.task_name = task_name
        t.save()


def remove_task_name(apps, schema_editor):
    """
    This doesn't need to be implemented as the task names will be deleted when the field is removed
    """
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('carrot', '0002_add_task_name'),
    ]

    operations = [
        migrations.RunPython(add_task_name, remove_task_name),
    ]
