# Generated by Django 2.2.8 on 2019-12-12 06:42

from django.db import migrations


def remove_latlng_columns_in_data(apps, schema_editor):
    Route = apps.get_model("routes", "Route")
    for route in Route.objects.all():
        try:
            route.data.drop(columns=["lat", "lng"], inplace=True)
        except KeyError:
            continue
        route.save(update_fields=["data"])


def restore_latlng_columns_in_data(apps, schema_editor):
    Route = apps.get_model("routes", "Route")
    for route in Route.objects.all():

        # transform route geometry to 4326
        route.geom.transform(4326)

        # pandas for the win: we cannot start from the route geometry
        # because it has a different number of coords than the number of rows in data
        route.data["lng"], route.data["lat"] = zip(  # unpack list of coords tupples
            *(route.data["length"] / route.data["length"].max())  # line location
            .apply(lambda x: route.geom.interpolate_normalized(x).coords)  # get Point
            .to_list()  # dump list of coords tupples
        )

        route.save(update_fields=["data"])


class Migration(migrations.Migration):

    dependencies = [
        ('routes', '0034_route_garmin_id'),
    ]

    operations = [
        migrations.RunPython(
            remove_latlng_columns_in_data, restore_latlng_columns_in_data
        )
    ]
