# Generated by Django 4.1.7 on 2023-03-27 18:19

import itertools
from django.db import migrations
from django.contrib.auth.management import create_permissions


def apply_migration(apps, schema_editor):
    # Force the creation of the permission objects we'll need
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, verbosity=0)
        app_config.models_module = None
    db_alias = schema_editor.connection.alias
    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")
    # Create our groups
    Group.objects.using(db_alias).bulk_create(
        [
            Group(name="Administrators"),
            Group(name="Classifier Managers"),
            Group(name="PermissionGroup Managers"),
            Group(name="Project Managers"),
            Group(name="Version Managers"),
            Group(name="Editors"),
        ]
    )
    # Now assign permissions
    group = Group.objects.using(db_alias).get(name="Classifier Managers")
    classifier_permissions = Permission.objects.filter(codename__endswith='classifier')
    group.permissions.set(classifier_permissions)

    group = Group.objects.using(db_alias).get(name="Project Managers")
    project_permissions = Permission.objects.filter(codename__endswith='project')
    group.permissions.set(project_permissions)

    group = Group.objects.using(db_alias).get(name="PermissionGroup Managers")
    permissiongroup_permissions = Permission.objects.filter(codename__endswith='permissiongroup')
    group.permissions.set(permissiongroup_permissions)

    group = Group.objects.using(db_alias).get(name="Version Managers")
    version_permissions = Permission.objects.filter(codename__endswith='version')
    group.permissions.set(version_permissions)

    group = Group.objects.using(db_alias).get(name="Administrators")
    group.permissions.set(
        itertools.chain(
            classifier_permissions,
            permissiongroup_permissions,
            project_permissions,
            version_permissions
        )
    )
    group = Group.objects.using(db_alias).get(name="Editors")
    group.permissions.set(
        itertools.chain(
            project_permissions,
            version_permissions
        )
    )


def revert_migration(apps, schema_editor):
    Group = apps.get_model("auth", "Group")
    Group.objects.filter(
        name__in=[
            "Classifier Managers",
            "PermissionGroup Managers",
            "Project Managers",
            "Version Managers",
            "Editors",
            "Administrators",
        ]
    ).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('sphinxhostingcore', '0009_SphinxPage_searchable'),
    ]

    operations = [migrations.RunPython(apply_migration, revert_migration)]
