# Generated by Django 5.1.3 on 2024-11-19 09:29

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


class Migration(migrations.Migration):

    dependencies = [
        ("models", "11408_loadstaging_sortorder"),
    ]

    def add_grouping_node(apps, schema_editor):
        NodeGroup = apps.get_model("models", "NodeGroup")
        nodegroups_with_nodes = NodeGroup.objects.filter(node__gt=0).distinct()
        for nodegroup in nodegroups_with_nodes:
            nodegroup.grouping_node_id = nodegroup.pk
        NodeGroup.objects.bulk_update(nodegroups_with_nodes, ["grouping_node_id"])

        PublishedGraph = apps.get_model("models", "PublishedGraph")
        published_graphs = PublishedGraph.objects.all()
        for published_graph in published_graphs:
            for nodegroup_dict in published_graph.serialized_graph["nodegroups"]:
                nodegroup_dict["grouping_node_id"] = nodegroup_dict["nodegroupid"]
        PublishedGraph.objects.bulk_update(published_graphs, ["serialized_graph"])

    def remove_grouping_node(apps, schema_editor):
        PublishedGraph = apps.get_model("models", "PublishedGraph")
        published_graphs = PublishedGraph.objects.all()
        for published_graph in published_graphs:
            for nodegroup_dict in published_graph.serialized_graph["nodegroups"]:
                nodegroup_dict.pop("grouping_node_id", None)
        PublishedGraph.objects.bulk_update(published_graphs, ["serialized_graph"])

    operations = [
        migrations.AddField(
            model_name="nodegroup",
            name="grouping_node",
            field=models.OneToOneField(
                blank=True,
                db_column="groupingnodeid",
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="grouping_node_nodegroup",
                to="models.node",
            ),
        ),
        migrations.AlterField(
            model_name="nodegroup",
            name="cardinality",
            field=models.CharField(
                blank=True, choices=[("1", "1"), ("n", "n")], default="1", max_length=1
            ),
        ),
        migrations.AlterField(
            model_name="nodegroup",
            name="parentnodegroup",
            field=models.ForeignKey(
                blank=True,
                db_column="parentnodegroupid",
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name="children",
                related_query_name="child",
                to="models.nodegroup",
            ),
        ),
        migrations.RunPython(add_grouping_node, remove_grouping_node),
    ]
