# Generated by Django 2.2.17 on 2021-01-14 09:02

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


def forwards_func(apps, schema_editor):
    BaseLocations = apps.get_model('locations', 'Locations')
    LocationsTranslation = apps.get_model('locations', 'LocationsTranslation')

    for object in BaseLocations.objects.all():
        object_translation = LocationsTranslation.objects.get(
            master_id=object.pk,
            language_code=settings.LANGUAGE_CODE
        )
        if object_translation is not None:
            object_translation.country = object.country_old
            object_translation.save()


def backwards_func(apps, schema_editor):
    BaseLocations = apps.get_model('locations', 'Locations')
    LocationsTranslation = apps.get_model('locations', 'LocationsTranslation')

    for object in BaseLocations.objects.all():
        translation = _get_translation(object, LocationsTranslation)
        object.country_old = translation.country
        object.save()   # Note this only calls Model.save()


def _get_translation(object, MyModelTranslation):
    translations = MyModelTranslation.objects.filter(master_id=object.pk)
    try:
        # Try default translation
        return translations.get(language_code=settings.LANGUAGE_CODE)
    except ObjectDoesNotExist:
        try:
            # Try default language
            return translations.get(language_code=settings.PARLER_DEFAULT_LANGUAGE_CODE)
        except ObjectDoesNotExist:
            # Maybe the object was translated only in a specific language?
            # Hope there is a single
            return translations.get()


class Migration(migrations.Migration):

    dependencies = [
        ('locations', '0012_locationstranslation_country'),
    ]

    operations = [
        migrations.RunPython(forwards_func, backwards_func),
        migrations.RemoveField(
            model_name='locations',
            name='country_old',
        ),
    ]
