# Generated by Django 2.2 on 2019-06-24 12:46

from django.db import migrations, models


def update_part_revisions(apps, schema_editor):
    Part = apps.get_model('bom', 'Part')
    PartRevision = apps.get_model('bom', 'PartRevision')

    for p in Part.objects.all():
        revs = PartRevision.objects.filter(part=p)
        rev_numbers = revs.values_list('revision', flat=True)
        for rev_number in rev_numbers:
            if list(rev_numbers).count(rev_number) > 1:
                revs_to_update = list(revs.filter(revision=rev_number).order_by('timestamp'))
                count_revs_to_update = int(PartRevision.objects.filter(part=p, revision=rev_number).count())
                idx = -1
                for r in revs_to_update:
                    idx += 1
                    if idx < (count_revs_to_update - 1):
                        timestamp = r.timestamp
                        r.revision = '{}.{}'.format(r.revision, idx)
                        # TODO: Don't update timestamps
                        r.timestamp = timestamp
                        r.save()


class Migration(migrations.Migration):

    dependencies = [
        ('bom', '0018_auto_20190616_2143'),
    ]

    operations = [
        migrations.AlterField(
            model_name='partrevision',
            name='revision',
            field=models.CharField(db_index=True, max_length=4),
        ),
        migrations.RunPython(update_part_revisions),
        migrations.AlterUniqueTogether(
            name='partrevision',
            unique_together={('part', 'revision')},
        ),
    ]
