# Generated by Django 2.2.5 on 2019-11-03 12:23

from django.db import migrations

from weblate.utils.state import STATE_READONLY


def migrate_source_strings(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    Unit = apps.get_model("trans", "Unit")
    Source = apps.get_model("trans", "Source")
    Translation = apps.get_model("trans", "Translation")
    translations = {}
    for source in Source.objects.using(db_alias).iterator():
        component = source.component

        # Find matching target unit
        try:
            language_unit = Unit.objects.using(db_alias).filter(
                translation__component=component, id_hash=source.id_hash
            )[0]
        except IndexError:
            # No matching translation, discard the source, probably outdated
            continue

        # Get or create source strings translation
        if component.pk not in translations:
            language = component.project.source_language
            translation = Translation.objects.using(db_alias).get_or_create(
                language=language,
                component=component,
                defaults={
                    "check_flags": "read-only",
                    "language_code": language.code,
                    "plural": language.plural_set.filter(source=0)[0],
                },
            )[0]
            translations[component.pk] = translation
        else:
            translation = translations[component.pk]

        # Create matching source unit
        kwargs = {
            "extra_flags": source.check_flags,
            "extra_context": source.context,
            "source": language_unit.source,
            "target": language_unit.source,
            "context": language_unit.context,
            "position": language_unit.position,
            "comment": language_unit.comment,
            "location": language_unit.location,
            "state": STATE_READONLY,
            "content_hash": language_unit.content_hash,
        }
        Unit.objects.using(db_alias).get_or_create(
            translation=translation, id_hash=source.id_hash, defaults=kwargs
        )

        # Set timestamp and extra flags and context on all units
        Unit.objects.using(db_alias).filter(
            translation__component=component, id_hash=source.id_hash
        ).update(
            timestamp=source.timestamp,
            extra_flags=source.check_flags,
            extra_context=source.context,
        )


class Migration(migrations.Migration):

    dependencies = [("trans", "0045_auto_20191103_1029")]

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