# Generated by Django 4.1.2 on 2023-02-16 12:05

# Replace Editor model with a permissions group for editors

from django.db import migrations
from django.contrib.auth.management import create_permissions
from django.db.models import Count


def convert_editors(apps, schema_editor):
    # Ensure that permissions exist
    # See https://code.djangoproject.com/ticket/23422#comment:29
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None
    Permission = apps.get_model("auth", "Permission")
    Group = apps.get_model("auth", "Group")
    ContentType = apps.get_model("contenttypes", "ContentType")
    website_ct = ContentType.objects.get(
        app_label="website", model="publication"
    )
    add_perm, _created = Permission.objects.get_or_create(
        content_type=website_ct, codename="add_publication"
    )
    change_perm, _created = Permission.objects.get_or_create(
        content_type=website_ct, codename="change_publication"
    )
    website_editor_group = (
        Group.objects.annotate(perm_count=Count("permissions"))
        .filter(perm_count=2)
        .filter(permissions=add_perm)
        .filter(permissions=change_perm)
        .first()
    )
    if not website_editor_group:
        website_editor_group = Group.objects.create(name="Website Editors")
        website_editor_group.permissions.add(add_perm)
        website_editor_group.permissions.add(change_perm)
    Editor = apps.get_model("website", "Editor")
    editors = Editor.objects.all().iterator()
    for editor in editors:
        editor.user.groups.add(website_editor_group)


class Migration(migrations.Migration):
    dependencies = [
        ("contenttypes", "0002_remove_content_type_name"),
        ("website", "0011_alter_authors"),
    ]

    operations = [
        migrations.RunPython(convert_editors),
    ]
