# Generated by Django 2.2.5 on 2019-11-03 13:37

from django.db import migrations


def migrate_source_strings(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    Unit = apps.get_model("trans", "Unit")
    Screenshot = apps.get_model("screenshots", "Screenshot")
    Translation = apps.get_model("trans", "Translation")
    translations = {}
    for screenshot in Screenshot.objects.using(db_alias).iterator():
        for source in screenshot.sources.iterator():
            component = source.component
            if component.pk not in translations:
                translations[component.pk] = Translation.objects.using(db_alias).get(
                    language=component.project.source_language, component=component
                )
            try:
                unit = Unit.objects.using(db_alias).filter(
                    id_hash=source.id_hash, translation=translations[component.pk]
                )[0]
            except IndexError:
                continue
            screenshot.units.add(unit)


class Migration(migrations.Migration):

    dependencies = [
        ("screenshots", "0004_screenshot_units"),
        ("trans", "0046_source_strings"),
    ]

    operations = [
        migrations.RunPython(
            migrate_source_strings, migrations.RunPython.noop, elidable=True
        )
    ]
