# Generated by Django 3.2.15 on 2022-08-12 16:28

from django.db import migrations, models, transaction


def convert_artifact_to_snippets(apps, schema_editor):
    """Create snippet from artifact and remove artifact."""
    with transaction.atomic():
        Modulemd = apps.get_model('rpm', 'Modulemd')
        ModulemdDefaults = apps.get_model('rpm', 'ModulemdDefaults')
        ContentArtifact = apps.get_model('core', 'ContentArtifact')
        Artifact = apps.get_model('core', 'Artifact')
        modules_with_snippet = []
        defaults_with_snippet = []
        content_artifacts_to_delete = []
        artifacts_to_delete = []

        for module in Modulemd.objects.all():
            artifact = module._artifacts.get()
            module.snippet = artifact.file.read()
            content_artifact = ContentArtifact.objects.get(artifact__pk=artifact.pk)
            content_artifacts_to_delete.append(content_artifact.pk)
            artifacts_to_delete.append(artifact.pk)
            modules_with_snippet.append(module)

        for default in ModulemdDefaults.objects.all():
            artifact = default._artifacts.get()
            default.snippet = artifact.file.read()
            content_artifact = ContentArtifact.objects.get(artifact__pk=artifact.pk)
            content_artifacts_to_delete.append(content_artifact.pk)
            artifacts_to_delete.append(artifact.pk)
            defaults_with_snippet.append(default)

        Modulemd.objects.bulk_update(
            modules_with_snippet,
            ['snippet']
        )

        ModulemdDefaults.objects.bulk_update(
            defaults_with_snippet,
            ['snippet']
        )

        ContentArtifact.objects.filter(pk__in=content_artifacts_to_delete).delete()
        Artifact.objects.filter(pk__in=artifacts_to_delete).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('rpm', '0043_textfield_conversion'),
    ]

    operations = [
        migrations.AddField(
            model_name='modulemd',
            name='snippet',
            field=models.TextField(default='snippet'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='modulemddefaults',
            name='snippet',
            field=models.TextField(default='snippet'),
            preserve_default=False,
        ),
        migrations.RunPython(convert_artifact_to_snippets),
    ]
