# Generated by Django 3.1.7 on 2021-11-04 20:32

from typing import Iterable, List, TypeVar

from django.db import migrations
from django.db.models import F

T = TypeVar("T")


def batch(batch_size: int, iterable: Iterable[T]) -> Iterable[List[T]]:
    collected = []
    for entry in iterable:
        collected.append(entry)
        if len(collected) >= batch_size:
            yield collected
            collected = []
    if len(collected) > 0:
        yield collected


def forwards(apps, schema_editor):
    Namespace = apps.get_model("repository", "Namespace")
    Package = apps.get_model("repository", "Package")
    packages = Package.objects.annotate(
        owner_name=F("owner__name"), owner_primary_key=F("owner__pk")
    ).iterator()
    for p in packages:
        namespace_for_package = p.owner.namespaces.filter(
            name__iexact=p.owner_name
        ).first()
        if not namespace_for_package:
            namespace_for_package = Namespace.objects.create(
                name=p.owner_name, team_id=p.owner_primary_key
            )
        p.namespace = namespace_for_package
        p.save()


def backwards(apps, schema_editor):
    Package = apps.get_model("repository", "Package")
    package_ids = Package.objects.values_list("id", flat=True).iterator()
    for ids in batch(2000, package_ids):
        Package.objects.filter(id__in=ids).update(namespace=None)


class Migration(migrations.Migration):

    dependencies = [
        ("repository", "0030_package_namespace"),
    ]

    operations = [
        migrations.RunPython(forwards, backwards),
    ]
