# Generated by Django 2.2.14 on 2020-08-03 19:21

from django.db import migrations

def rename_update_collections(apps, schema):
    """Insure every UpdateCollection associated with an Advisory has a unique name"""
    UpdateCollection = apps.get_model("rpm", "UpdateCollection")
    UpdateRecord = apps.get_model("rpm", "UpdateRecord")
    modified_collections = []
    for advisory in UpdateRecord.objects.all():
        names = {}
        for collection in advisory.collections.all():
            if collection.name in names.keys():
                orig_name = collection.name
                new_name = "{}_{}".format(orig_name, names[orig_name])
                collection.name = new_name
                names[orig_name] += 1
                modified_collections.append(collection)
            else:
                names[collection.name] = 0
    UpdateCollection.objects.bulk_update(modified_collections, ['name'])

def delete_orphan_collections(apps, schema):
    """Delete orphaned collections"""
    UpdateCollection = apps.get_model("rpm", "UpdateCollection")
    UpdateCollection.objects.filter(update_record=None).delete()

def map_update_collection_to_update_record(apps, schema):
    """Point every collection to its/a/single UpdateRecord"""
    UpdateCollection = apps.get_model("rpm", "UpdateCollection")
    for collection in UpdateCollection.objects.all():
        # At this point we can assume There Will Be Only One
        ur = collection.update_record.all().first()
        collection._update_record = ur
        collection.save()

class Migration(migrations.Migration):

    dependencies = [
        ('rpm', '0018_updatecollection__update_record'),
    ]

    # There are three data-shapes that need to be handled when moving from
    # many-to-many, unconstrained, to 1-to-1 with constraints:
    # * one UpdateCollection points to multiple UpdateRecords - new
    #   UpdateCollections must be created. Fixed previously under #7291.
    # * several UpdateCollections belonging to the same UpdateRecord have the
    #   same name - names must be made unique (rename_update_collections)
    # * UpdateCollections may not point to ANY UpdateRecords - orphaned
    #   UpdateCollections must be removed (delete_orphan_collections)
    # Only once we fix UpdateCollection data, do we point every Collection's
    # _update_record at its (now-single) Advisory (map_update_collection_to_update_record)
    operations = [
        migrations.RunPython(rename_update_collections),
        migrations.RunPython(delete_orphan_collections),
        migrations.RunPython(map_update_collection_to_update_record),
    ]
