# Generated by Django 3.0.3 on 2020-08-25 10:28

from django.db import migrations, transaction, models


def complete_to_completed_tasks(apps, schema_editor):
    Labels = apps.get_model('image_labelling_tool', 'Labels')
    LabellingTask = apps.get_model('image_labelling_tool', 'LabellingTask')

    with transaction.atomic():
        if Labels.objects.filter(complete=True).exists():
            # There are some Label instances that are marked as finished
            # Create 'finished' task if it does not exist
            try:
                finished_task = LabellingTask.objects.get(name='finished')
            except LabellingTask.DoesNotExist:
                finished_task = LabellingTask(name='finished', human_name='(old) Finished', enabled=True)
                finished_task.save()

            rows = Labels.objects.all()
            for row in rows:
                if row.complete:
                    row.completed_tasks.add(finished_task)
                    row.save()


class Migration(migrations.Migration):
    dependencies = [
        ('image_labelling_tool', '0004_auto_20200223_1009'),
    ]

    operations = [
        migrations.CreateModel(
            name='LabellingTask',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('enabled', models.BooleanField(default=True)),
                ('name', models.CharField(max_length=256)),
                ('human_name', models.CharField(max_length=256)),
                ('order_key', models.IntegerField(default=0)),
            ],
        ),
        migrations.AddField(
            model_name='labels',
            name='completed_tasks',
            field=models.ManyToManyField(to='image_labelling_tool.LabellingTask'),
        ),
        migrations.RunPython(complete_to_completed_tasks),
    ]
