# Generated by Django 4.2.1 on 2023-10-03 13:42

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


def forwards_func(apps, schema_editor):
    NodeMessage = apps.get_model("mesh", "NodeMessage")
    MeshNode = apps.get_model("mesh", "MeshNode")

    NodeMessage.objects.filter(uplink_node=None).delete()

    nodes = {node.address: node for node in MeshNode.objects.all()}

    for msg in NodeMessage.objects.all():
        if msg.data["src"] not in nodes:
            nodes[msg.data["src"]] = MeshNode.objects.create(address=msg.data["src"])
        msg.src_node = nodes[msg.data["src"]]
        msg.save()


class Migration(migrations.Migration):

    dependencies = [
        ('mesh', '0003_meshnode_name'),
    ]

    operations = [
        migrations.RenameField(
            model_name='nodemessage',
            old_name='node',
            new_name='uplink_node',
        ),
        migrations.RemoveField(
            model_name='meshnode',
            name='firmware',
        ),
        migrations.RemoveField(
            model_name='meshnode',
            name='parent_node',
        ),

        migrations.AddField(
            model_name='nodemessage',
            name='src_node',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT,
                                    related_name='received_messages', to='mesh.meshnode', verbose_name='node'),
        ),
        migrations.AlterField(
            model_name='nodemessage',
            name='uplink_node',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT,
                                    related_name='relayed_messages', to='mesh.meshnode', verbose_name='uplink node'),
        ),

        migrations.RunPython(forwards_func, migrations.RunPython.noop),

        migrations.AlterField(
            model_name='nodemessage',
            name='src_node',
            field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='received_messages',
                                    to='mesh.meshnode', verbose_name='node'),
        ),
        migrations.AlterField(
            model_name='nodemessage',
            name='uplink_node',
            field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='relayed_messages',
                                    to='mesh.meshnode', verbose_name='uplink node'),
        ),
    ]
