# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-11 17:06
from __future__ import unicode_literals

import logging

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

logger = logging.getLogger(__name__)


def forwards_func(apps, schema_editor):
    Subject = apps.get_model('course_metadata', 'Subject')
    SubjectTranslation = apps.get_model('course_metadata', 'SubjectTranslation')

    for subject in Subject.objects.all():
        SubjectTranslation.objects.create(
            master_id=subject.pk,
            language_code=settings.PARLER_DEFAULT_LANGUAGE_CODE,
            name_t=subject.name,
            subtitle_t=subject.subtitle,
            description_t=subject.description
        )


def backwards_func(apps, schema_editor):
    Subject = apps.get_model('course_metadata', 'Subject')
    SubjectTranslation = apps.get_model('course_metadata', 'SubjectTranslation')

    for subject in Subject.objects.all():
        try:
            translation = SubjectTranslation.objects.get(master_id=subject.pk, language_code=settings.LANGUAGE_CODE)
            subject.name = translation.name_t
            subject.subtitle = translation.subtitle_t
            subject.description = translation.description_t
            subject.save()  # Note this only calls Model.save()
        except ObjectDoesNotExist:
            # nothing to migrate
            logger.exception('Migrating data from SubjectTranslation for master_id={} DoesNotExist'.format(subject.pk))

class Migration(migrations.Migration):
    dependencies = [
        ('course_metadata', '0060_create_subjecttranslations_models'),
    ]

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