# Generated by Django 3.1.7 on 2022-07-28 11:49
from typing import Iterable, List, TypeVar

from django.db import migrations

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 noop(*args, **kwargs):
    pass


def forwards(apps, schema_editor):
    Community = apps.get_model("community", "Community")
    for entry in batch(
        2000,
        Community.objects.exclude(sites=None).values_list("id", flat=True).iterator(),
    ):
        query = Community.objects.filter(id__in=entry).prefetch_related("sites")
        for community in query:
            site = community.sites.all()[0]

            # We need to set update_dimension_fields to noop as the storage
            # backend isn't available during migrations. Instead, we populate
            # the fields from existing data in the CommunitySite
            community.background_image.field.update_dimension_fields = noop
            community.background_image = site.background_image
            community.background_image_width = site.background_image_width
            community.background_image_height = site.background_image_height

            # Same as above here
            community.icon.field.update_dimension_fields = noop
            community.icon = site.icon
            community.icon_width = site.icon_width
            community.icon_height = site.icon_height

            community.slogan = site.slogan
            community.description = site.description
            community.save()


class Migration(migrations.Migration):

    dependencies = [
        ("community", "0019_add_community_metadata"),
    ]

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