# Generated by Django 2.2.17 on 2021-01-05 21:39

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


def populate_last_updated_fields(apps, schema_editor):
    from peeringdb_server.util import disable_auto_now_and_save

    Network = apps.get_model("peeringdb_server", "Network")

    print("This migration may take a few minutes ...")

    for network in Network.handleref.all():
        try:
            latest_netfac = network.netfac_set.filter(updated__isnull=False).latest(
                "updated"
            )
            network.netfac_updated = latest_netfac.updated
        except ObjectDoesNotExist:
            pass
        try:
            latest_netixlan = network.netixlan_set.filter(updated__isnull=False).latest(
                "updated"
            )
            network.netixlan_updated = latest_netixlan.updated
        except ObjectDoesNotExist:
            pass

        try:
            latest_poc = network.poc_set.filter(updated__isnull=False).latest("updated")
            network.poc_updated = latest_poc.updated
        except ObjectDoesNotExist:
            pass

        disable_auto_now_and_save(network)


class Migration(migrations.Migration):
    dependencies = [
        ("peeringdb_server", "0062_adjust_geo_fields"),
    ]

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