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

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


def _get_munigeo_models(apps):
    AD = apps.get_model('munigeo', 'AdministrativeDivision')
    ADTranslation = apps.get_model('munigeo', 'AdministrativeDivisionTranslation')

    Municipality = apps.get_model('munigeo', 'Municipality')
    MunicipalityTranslation = apps.get_model('munigeo', 'MunicipalityTranslation')

    Street = apps.get_model('munigeo', 'Street')
    StreetTranslation = apps.get_model('munigeo', 'StreetTranslation')

    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):
            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):
            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),
    ]
