# Generated by Django 2.2.1 on 2019-06-25 05:06

from django.db import migrations

from weblate.formats.auto import detect_filename


def resolve_auto_format(apps, schema_editor):
    Addon = apps.get_model("addons", "Addon")
    db_alias = schema_editor.connection.alias
    for addon in Addon.objects.using(db_alias).filter(
        name="weblate.discovery.discovery"
    ):
        if addon.configuration["file_format"] == "auto":
            detect = detect_filename(addon.configuration["match"].replace("\\.", "."))
            if detect is None:
                raise Exception(
                    "Existing component discovery with auto format, can not detect "
                    "file format. Please edit the format manually and rerun "
                    "migration. Affected component: {}/{}".format(
                        addon.component.project.slug, addon.component.slug
                    )
                )

            addon.configuration["file_format"] = detect.format_id
            addon.save()


class Migration(migrations.Migration):

    dependencies = [("addons", "0016_language_consistency")]

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