# Generated by Django 2.0.5 on 2018-07-16 13:04

from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import migrations


def _get_munigeo_models(apps):
    AD = apps.get_model("munigeo", "AdministrativeDivision")  # noqa: N806
    ADTranslation = apps.get_model("munigeo", "AdministrativeDivisionTranslation")  # noqa: N806

    Municipality = apps.get_model("munigeo", "Municipality")  # noqa: N806
    MunicipalityTranslation = apps.get_model("munigeo", "MunicipalityTranslation")  # noqa: N806

    Street = apps.get_model("munigeo", "Street")  # noqa: N806
    StreetTranslation = apps.get_model("munigeo", "StreetTranslation")  # noqa: N806

    return [
        (AD, ADTranslation),
        (Municipality, MunicipalityTranslation),
        (Street, StreetTranslation),
    ]


def forwards_func(apps, schema_editor):
    for lang_code, _ in settings.LANGUAGES:
        name_field_key = "name_" + lang_code

        for Model, ModelTranslation in _get_munigeo_models(apps):  # noqa: N806
            for object in Model.objects.all():
                translated_name = getattr(object, name_field_key)
                if translated_name:
                    ModelTranslation.objects.create(
                        master_id=object.pk,
                        language_code=lang_code,
                        name_parler=translated_name,
                    )


def backwards_func(apps, schema_editor):
    for lang_code, _ in settings.LANGUAGES:
        name_field_key = "name_" + lang_code

        for Model, ModelTranslation in _get_munigeo_models(apps):  # noqa: N806
            for object in Model.objects.all():
                try:
                    translation = ModelTranslation.objects.get(
                        master_id=object.pk, language_code=lang_code
                    )
                    setattr(object, name_field_key, translation.name_parler)
                    object.save()
                except ObjectDoesNotExist:
                    pass


class Migration(migrations.Migration):
    dependencies = [
        ("munigeo", "0002_add_parler_translations"),
    ]

    operations = [
        migrations.RunPython(forwards_func, backwards_func),
    ]
