# Generated by Django 2.2.14 on 2021-01-26 00:25

from django.db import migrations, models
import multiselectfield.db.fields


def make_pinned_reports_unique(apps, schema_editor):
    PinnedReport = apps.get_model("indicators", "PinnedReport")
    db_alias = schema_editor.connection.alias
    # find all duplicates
    duplicates = PinnedReport.objects.values("tola_user", "name", "program").order_by().annotate(
        records=models.Count('id')).filter(records__gt=1)
    # iterate through duplicates:
    for duplicate in duplicates:
        # iterate through specific copies of this duplicate:
        these_duplicates = PinnedReport.objects.filter(
            tola_user=duplicate['tola_user'], name=duplicate['name'], program=duplicate['program']
        ).order_by('id')
        # leave the first one, but add a "1" "2" etc. to the names of the others:
        for c, duplicate_report in enumerate(these_duplicates[1:]):
            duplicate_report.name = f"{duplicate_report.name} {c+1}"
            duplicate_report.save()




def non_reversible_migration(apps, schema_editor):
    """Operation to "reverse" an unreversible change"""
    pass


class Migration(migrations.Migration):

    dependencies = [
        ('indicators', '0093_kpi_to_indicator_type'),
    ]

    operations = [
        migrations.RunPython(make_pinned_reports_unique, non_reversible_migration),
        migrations.AddConstraint(
            model_name='pinnedreport',
            constraint=models.UniqueConstraint(fields=('name', 'tola_user', 'program'), name='unique_pinned_report_name'),
        ),
    ]
