# Generated by Django 2.2.16 on 2020-09-04 12:37

from django.db import migrations, models
import django.db.models.deletion
import django_lifecycle.mixins
import uuid


def initialize_namespaces(apps, schema_editor):
    """
    Look for all ContainerDistributions, and assign a namespace matching their base_path.
    """
    ContainerNamespace = apps.get_model('container', 'ContainerNamespace')
    ContainerDistribution = apps.get_model('container', 'ContainerDistribution')
    for distribution in ContainerDistribution.objects.all():
        namespace_name = distribution.base_path.split('/')[0]
        distribution.namespace = ContainerNamespace.objects.get_or_create(name=namespace_name)[0]
        distribution.save()


class Migration(migrations.Migration):

    dependencies = [
        ('container', '0008_include_exclude_tags'),
    ]

    operations = [
        migrations.CreateModel(
            name='ContainerNamespace',
            fields=[
                ('pulp_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
                ('pulp_created', models.DateTimeField(auto_now_add=True)),
                ('pulp_last_updated', models.DateTimeField(auto_now=True, null=True)),
                ('name', models.CharField(db_index=True, max_length=255)),
            ],
            options={
                'unique_together': {('name',)},
            },
            bases=(django_lifecycle.mixins.LifecycleModelMixin, models.Model),
        ),
        migrations.AddField(
            model_name='containerdistribution',
            name='namespace',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='container_distributions', to='container.ContainerNamespace'),
        ),
        # Reverting that step is simply removing the new relation and table.
        migrations.RunPython(initialize_namespaces, reverse_code=migrations.RunPython.noop),
    ]
