# Generated by Django 2.1.2 on 2019-05-27 01:17
from distutils.version import StrictVersion

import django.db.models.deletion
from django.db import migrations, models
from django.db.models import Case, When


def get_latest(package):
    versions = package.versions.filter(is_active=True).values_list(
        "pk", "version_number"
    )
    ordered = sorted(versions, key=lambda version: StrictVersion(version[1]))
    pk_list = [version[0] for version in reversed(ordered)]
    preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)])
    return package.versions.filter(pk__in=pk_list).order_by(preserved).first()


def forwards(apps, schema_editor):
    Package = apps.get_model("repository", "Package")
    for package in Package.objects.all():
        package.latest = get_latest(package)
        package.save()


class Migration(migrations.Migration):

    dependencies = [
        ("repository", "0012_package_is_deprecated"),
    ]

    operations = [
        migrations.AddField(
            model_name="package",
            name="latest",
            field=models.ForeignKey(
                null=True,
                on_delete=django.db.models.deletion.SET_NULL,
                related_name="+",
                to="repository.PackageVersion",
            ),
        ),
        migrations.RunPython(forwards),
    ]
