# Generated by Django 3.0.3 on 2020-02-21 10:19

from django.db import migrations

from weblate.trans.util import split_plural
from weblate.utils.stats import BaseStats


def fixup_num_words(apps, schema_editor):
    db_alias = schema_editor.connection.alias

    Unit = apps.get_model("trans", "Unit")

    translations = {}

    for unit in Unit.objects.using(db_alias).filter(num_words=0):
        unit.num_words = len(split_plural(unit.source)[0].split())
        unit.save(update_fields=["num_words"])
        if unit.translation_id not in translations:
            translations[unit.translation_id] = unit.translation

    # Invalidate caches
    for translation in translations.values():
        BaseStats(translation).invalidate()
        BaseStats(translation.component).invalidate()
        BaseStats(translation.component.project).invalidate()


class Migration(migrations.Migration):

    dependencies = [("trans", "0061_auto_20200218_1108")]

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