# Generated by Django 2.2.5 on 2019-10-21 06:10

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


def forwards_func(apps, schema_editor):
    LoginMethod = apps.get_model('users', 'LoginMethod')
    LoginMethodTranslation = apps.get_model('users', 'LoginMethodTranslation')

    for obj in LoginMethod.objects.all():
        LoginMethodTranslation.objects.create(
            master_id=obj.pk,
            language_code=settings.LANGUAGE_CODE,
            name_t=obj.name,
            short_description_t=obj.short_description,
        )


def backwards_func(apps, schema_editor):
    LoginMethod = apps.get_model('users', 'LoginMethod')
    LoginMethodTranslation = apps.get_model('users', 'LoginMethodTranslation')

    for obj in LoginMethod.objects.all():
        translation = _get_translation(obj, LoginMethodTranslation)
        obj.name = translation.name_t
        obj.short_description = translation.short_description_t
        obj.save()


def _get_translation(obj, translation_class):
    translations = translation_class.objects.filter(master_id=obj.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 translation
            return translations.get()


class Migration(migrations.Migration):

    dependencies = [
        ('users', '0018_make_login_methods_translatable'),
    ]

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