# Generated by Django 4.2.7 on 2024-08-07 19:37

from django.db import migrations


def _from_db_value(value, expression, connection):
    # for bypass clean_choices validation
    if value is None:
        return None
    if not value or value == "[]":
        return []
    return value.split(",")


def forward(apps, schema_editor):
    Facility = apps.get_model("django_peeringdb", "Facility")
    updated_field = Facility._meta.get_field("updated")
    updated_field_auto_now = updated_field.auto_now
    from_db_value = Facility._meta.get_field("available_voltage_services").from_db_value
    invalid_voltage_values = ["120 VAC", "208 VAC", "240 VAC"]

    try:
        # overide from_db_value method
        # because this method calls "clean_choices" resulting in a validation error when retrieving all facilites.
        Facility._meta.get_field(
            "available_voltage_services"
        ).from_db_value = _from_db_value
        facilities = Facility.handleref.all()
        for facility in facilities:
            voltage = facility.available_voltage_services
            removed = []

            for invalid_voltage_value in invalid_voltage_values:
                try:
                    voltage.remove(invalid_voltage_value)
                    removed.append(invalid_voltage_value)
                except ValueError:
                    pass

            if removed:
                facility.available_voltage_services = voltage
                print(f"Removed {removed} from {facility}")
                facility.save()
    finally:
        Facility._meta.get_field(
            "available_voltage_services"
        ).from_db_value = from_db_value
        updated_field.auto_now = updated_field_auto_now


class Migration(migrations.Migration):
    dependencies = [
        (
            "django_peeringdb",
            "0033_alter_facility_property_alter_ixlan_rs_asn_and_more",
        ),
    ]

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