# Generated by Django 3.1.5 on 2021-01-26 21:00

from django.db import migrations


def delete_orphan_course_run_nodes(apps, schema_editor):
    """
    When we deleted the pages previously related to course runs, we
    forgot to delete the related nodes. Let's fix this.
    """
    TreeNode = apps.get_model("cms", "TreeNode")

    for node in (
        TreeNode.objects.filter(
            cms_pages__isnull=True, parent__cms_pages__course__isnull=False
        )
        .distinct()
        .iterator()
    ):
        # When deleting a node, we must also update its parent to decrement
        # its number of children
        parentpath = node.path[0 : (node.depth - 1) * 4]
        parent = TreeNode.objects.get(path=parentpath)
        node.delete()
        parent.numchild -= 1
        parent.save()


class Migration(migrations.Migration):

    dependencies = [("courses", "0027_auto_20210119_1411")]

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