# Generated by Django 3.2.12 on 2022-02-12 22:18

from django.db import migrations


def get_new_name(existing_names):
    index = 1
    name = "NEW"
    while name in existing_names:
        name = f"NEW{index}"
        index += 1
    return name


def create_unique_waypoint_names_editable(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    EditableRoute = apps.get_model("display", "EditableRoute")
    for editable_route in EditableRoute.objects.using(db_alias).all():
        existing_names = set()
        try:
            track = [item for item in editable_route.route if item["feature_type"] == "track"][0]
            track_points = track["track_points"]
            for item in track_points:
                if item["name"] in existing_names:
                    item["name"] = get_new_name(existing_names)
                existing_names.add(item["name"])
            editable_route.save()
        except IndexError:
            pass


def create_unique_waypoint_names_route(apps, schema_editor):
    db_alias = schema_editor.connection.alias
    Route = apps.get_model("display", "Route")
    for route in Route.objects.using(db_alias).all():
        existing_names = set()
        for waypoint in route.waypoints:
            if waypoint.name in existing_names:
                waypoint.name = get_new_name(existing_names)
            existing_names.add(waypoint.name)
        route.save()


class Migration(migrations.Migration):
    dependencies = [
        ('display', '0076_auto_20220211_2224'),
    ]

    operations = [
        migrations.RunPython(create_unique_waypoint_names_editable),
        migrations.RunPython(create_unique_waypoint_names_route)
    ]
