# 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 = [
        ('sites', '0002_alter_domain_unique'),
        ('core', '0034_invite_permission'),
    ]

    def _migrate_preference_models_to_unique(apps, schema_editor):
        from aleksis.core.models import GroupPreferenceModel, PersonPreferenceModel, SitePreferenceModel

        models = [GroupPreferenceModel, PersonPreferenceModel, SitePreferenceModel]

        for model in models:
            duplicates = {}
            db_alias = schema_editor.connection.alias
            for obj in model.objects.using(db_alias).all():
                key = f"{obj.instance.pk}__{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={('instance', 'section', 'name')},
        ),
        migrations.AlterUniqueTogether(
            name='personpreferencemodel',
            unique_together={('instance', 'section', 'name')},
        ),
        migrations.AlterUniqueTogether(
            name='sitepreferencemodel',
            unique_together={('instance', 'section', 'name')},
        ),
    ]
