# Generated by Django 2.2.3 on 2019-08-07 16:20

from django.db import migrations, models


featured = {}
def save_featured(apps, schema_editor):
    # Get all projects currently flagged as featured
    model = apps.get_model("project", "PublishedProject")
    projects = model.objects.filter(featured=True)

    # Save (PK: Increasing number) to dict
    i = 1
    for p in projects:
        featured[p.pk] = i
        i += 1

def migrate_featured(apps, schema_editor):
    model = apps.get_model("project", "PublishedProject")

    # Iterates the dict with featured projects
    for p, i in featured.items():
        # Update the new smallint field with the number assigned
        model.objects.filter(pk=p).update(featured=i)

def save_reverse(apps, schema_editor):
    # Get all projects currently flagged as featured
    model = apps.get_model("project", "PublishedProject")
    projects = model.objects.filter(featured__isnull=False)

    # Save (PK: Increasing number) to dict
    for p in projects:
        featured[p.pk] = True

def migrate_reverse(apps, schema_editor):
    model = apps.get_model("project", "PublishedProject")

    # Assings False as default
    model.objects.all().update(featured=False)

    # Iterates the dict with featured projects
    for p, i in featured.items():
        # Update the field to True
        model.objects.filter(pk=p).update(featured=True)
        

class Migration(migrations.Migration):

    dependencies = [
        ('project', '0029_publishedproject_display_publications'),
    ]

    operations = [
        # The current field is a boolean that flags featured projects
        # First we save the primary key for those projects
        # and assign a number that will be part of the initial ordering
        migrations.RunPython(save_featured, reverse_code=migrate_reverse),
        # Altering the field type from bool to int does not work on postgres
        # So we remove it and readd as a smallinteger 
        migrations.RemoveField(
            model_name='publishedproject',
            name='featured',
        ),
        migrations.AddField(
            model_name='publishedproject',
            name='featured',
            field=models.PositiveSmallIntegerField(null=True),
        ),
        # Repopulated it with the featured projects
        migrations.RunPython(migrate_featured, reverse_code=save_reverse),
        # Enforce contraint
        # The `featured` number should be unique across projects
        # As it will define the order of display
        migrations.AlterUniqueTogether(
            name='publishedproject',
            unique_together={('featured',), ('core_project', 'version')},
        ),
    ]
