# Generated by Django 2.2.9 on 2020-04-17 09:53

from django.db import migrations

from resolwe.flow.models.base import delete_chunked
from resolwe.flow.utils.iterators import iterate_fields


def delete_unreferenced_storages(apps, schema_editor):
    Data = apps.get_model("flow", "Data")
    Storage = apps.get_model("flow", "Storage")

    for data in Data.objects.iterator():
        referenced_storages = []
        for field_schema, fields in iterate_fields(
            data.output, data.process.output_schema
        ):
            if field_schema["type"].startswith("basic:json:"):
                name = field_schema["name"]
                referenced_storages.append(fields[name])

        data.storages.remove(*data.storages.exclude(pk__in=referenced_storages))

    delete_chunked(Storage.objects.filter(data__isnull=True), chunk_size=100)


class Migration(migrations.Migration):

    dependencies = [
        ("flow", "0044_datalocation_to_filestorage"),
    ]

    operations = [
        migrations.RunPython(delete_unreferenced_storages),
    ]
