# Generated by Django 3.0.7 on 2020-10-19 11:25

from django.db import migrations, models


def add_default_reference(apps, schema_editor):
    """
    Add a "default" build-order reference for any existing build orders.
    Best we can do is use the PK of the build order itself.
    """

    Build = apps.get_model('build', 'build')

    count = 0

    for build in Build.objects.all():

        build.reference = str(build.pk)
        build.save()
        count += 1

    if count > 0:
        print(f"\nUpdated build reference for {count} existing BuildOrder objects")


class Migration(migrations.Migration):

    atomic = False

    dependencies = [
        ('build', '0017_auto_20200426_0612'),
    ]

    operations = [
        # Initial operation - create a 'reference' field for the Build object:
        migrations.AddField(
            model_name='build',
            name='reference',
            field=models.CharField(help_text='Build Order Reference', blank=True, max_length=64, unique=False, verbose_name='Reference'),
        ),

        # Auto-populate the new reference field for any existing build order objects
        migrations.RunPython(
            add_default_reference,
            reverse_code=migrations.RunPython.noop
        ),

        # Now that each build has a non-empty, unique reference, update the field requirements!
        migrations.AlterField(
            model_name='build',
            name='reference',
            field=models.CharField(
                help_text='Build Order Reference',
                max_length=64,
                blank=False,
                unique=True,
                verbose_name='Reference'
            )
        )
    ]
