# Generated by Django 2.2.13 on 2020-07-03 03:45

from django.db import migrations
from django.db.models import Count, Q


def dedupe_ipaddrs(apps, schema_editor):
    NetIXLan = apps.get_model("peeringdb_server", "NetworkIXLan")

    duplicate_ippr4s = (
        NetIXLan.handleref.filter()
        .values("ipaddr4")
        .annotate(ipaddr4_count=Count("ipaddr4"))
        .filter(ipaddr4_count__gt=1)
        .values("ipaddr4")
    )

    netixlans_to_dedupe_4 = NetIXLan.handleref.filter(
        status="deleted", ipaddr4__in=duplicate_ippr4s
    )

    for n in netixlans_to_dedupe_4:
        n.ipaddr4 = None
        n.save()

    duplicate_ippr6s = (
        NetIXLan.handleref.filter()
        .values("ipaddr6")
        .annotate(ipaddr6_count=Count("ipaddr6"))
        .filter(ipaddr6_count__gt=1)
        .values("ipaddr6")
    )

    netixlans_to_dedupe_6 = NetIXLan.handleref.filter(
        status="deleted", ipaddr6__in=duplicate_ippr6s
    )

    for n in netixlans_to_dedupe_6:
        n.ipaddr6 = None
        n.save()

    active_dupes = NetIXLan.handleref.filter(
        Q(ipaddr4__in=duplicate_ippr4s) | Q(ipaddr6__in=duplicate_ippr6s),
        status="ok",
    )

    if active_dupes.count() == 0:
        print(
            "There are no active NetIXLan objects with repeated ipaddr4 or ipaddr6 values."
        )

    else:
        raise migrations.exceptions.DatabaseError(
            "There are active NetIXLan objects with repeated ipaddr4 or ipaddr6 values: {}".format(
                active_dupes
            )
        )


class Migration(migrations.Migration):
    dependencies = [
        ("peeringdb_server", "0036_ixlanprefix_in_dfz"),
    ]

    operations = [
        migrations.RunPython(dedupe_ipaddrs),
    ]
