# Generated by Django 3.2.11 on 2022-01-27 18:52

from email.headerregistry import Group
from django.db import migrations, models


class Migration(migrations.Migration):

    dependencies = [
        ('core', '0034_invite_permission'),
    ]

    def _migrate_preference_models_to_unique(apps, schema_editor):
        SitePreferenceModel = apps.get_model("core", "SitePreferenceModel")
        PersonPreferenceModel = apps.get_model("core", "PersonPreferenceModel")
        GroupPreferenceModel = apps.get_model("core", "GroupPreferenceModel")

        db_alias = schema_editor.connection.alias

        models = [GroupPreferenceModel, PersonPreferenceModel, SitePreferenceModel]

        for model in models:
            duplicates = {}
            for obj in model.objects.using(db_alias).all():
                key = f"{obj.section}__{obj.name}"
                duplicates.setdefault(key, [])
                duplicates[key].append(obj)

            for key, objs in duplicates.items():
                if len(objs) > 1:
                    found = False
                    for obj in objs:
                        if obj.value == obj.preference.default or found:
                            obj.delete()
                        else:
                            found = True


    operations = [
        migrations.RunPython(_migrate_preference_models_to_unique),
        migrations.AlterUniqueTogether(
            name='grouppreferencemodel',
            unique_together={('section', 'name')},
        ),
        migrations.AlterUniqueTogether(
            name='personpreferencemodel',
            unique_together={('section', 'name')},
        ),
        migrations.AlterUniqueTogether(
            name='sitepreferencemodel',
            unique_together={('section', 'name')},
        ),
    ]
