# Copyright © Michal Čihař <michal@weblate.org>
#
# SPDX-License-Identifier: GPL-3.0-or-later

# Generated by Django 3.0.7 on 2020-08-31 13:48

from django.db import migrations

from weblate.utils.hash import calculate_hash


def migrate_json_units(apps, schema_editor):
    Unit = apps.get_model("trans", "Unit")
    db_alias = schema_editor.connection.alias
    units = (
        Unit.objects.using(db_alias)
        .filter(
            translation__component__file_format__in=(
                "json",
                "arb",
                "go-i18n-json",
                "i18next",
                "webextension",
                "json-nested",
            )
        )
        .prefetch_related("translation__component")
    )
    for unit in units.iterator(chunk_size=1000):
        if unit.translation.component.template:
            newid = calculate_hash(unit.context)
        else:
            newid = calculate_hash(unit.source, unit.context)
        if newid != unit.id_hash:
            unit.id_hash = newid
            unit.save(update_fields=["id_hash"])


class Migration(migrations.Migration):
    dependencies = [
        ("trans", "0094_project_language_aliases"),
    ]

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