# Generated by Django 3.1.3 on 2020-11-23 10:46

import django.db.models.deletion
from django.db import migrations, models


def populate_direct_course(apps, schema_editor):
    """
    Populate the "direct_course" field with the information we currently have in the
    node tree, then delete all course run releated pages.
    """
    Page = apps.get_model("cms", "Page")
    Course = apps.get_model("courses", "Course")
    CourseRun = apps.get_model("courses", "CourseRun")
    CourseRunTranslation = apps.get_model("courses", "CourseRunTranslation")
    Title = apps.get_model("cms", "Title")

    for course_run in CourseRun.objects.iterator():
        try:
            course_run.direct_course = Course.objects.only("id").get(
                # Target courses that are ancestors of the course run
                extended_object__node=course_run.extended_object.node.parent,
                # Get the course in the same version as the course run
                extended_object__publisher_is_draft=course_run.extended_object.publisher_is_draft,
            )
        except Course.DoesNotExist as err:
            raise BadMigrationError(
                f"Course run {course_run.id:d} is not child of a course page."
            )

        # Create Django Parler translation objects for each language to hold the title
        for title_obj in Title.objects.filter(page=course_run.extended_object):
            CourseRunTranslation.objects.update_or_create(
                master=course_run,
                language_code=title_obj.language,
                defaults={"title": title_obj.title},
            )

        course_run.save()

    # Link draft and public instances with the new OneToOneField
    for course_run in CourseRun.objects.iterator():
        if course_run.public_extension_id:
            CourseRun.objects.filter(id=course_run.public_extension_id).update(
                draft_course_run=course_run
            )

    Page.objects.filter(courserun__isnull=False).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("courses", "0021_auto_20201202_1146"),
    ]

    operations = [
        migrations.RunPython(populate_direct_course, migrations.RunPython.noop),
    ]
