# Generated by Django 3.2.9 on 2022-08-13 05:33
from django.contrib.auth.models import Group, Permission
from django.conf import settings
import logging

from django.db import migrations

logger = logging.getLogger(__name__)

public_group_permissions = {
    settings.DEFAULT_PERMISSIONS_GROUP: [
        "create_corpusquery",
        "read_corpusquery",
        "update_corpusquery",
        "delete_corpusquery",
        "permission_corpusquery",
    ]
}


def add_group_permissions(apps, schema_editor):
    """Assign corpusquery permissions without forcing post_migrate."""
    for group in public_group_permissions:
        role, created = Group.objects.get_or_create(name=group)
        logger.info(f"{group} Group created")
        for perm in public_group_permissions[group]:
            try:
                logger.info(f"Permitting {group} to {perm}")
                role.permissions.add(Permission.objects.get(codename=perm))
            except Permission.DoesNotExist:
                logger.warning(
                    f"Permission '{perm}' does not exist yet; skipping assignment."
                )
        role.save()

    logger.info("Installation of default public access group COMPLETE!")


class Migration(migrations.Migration):
    dependencies = [
        ('users', '0009_setup_extract_permissions'),
    ]

    operations = [
        migrations.RunPython(add_group_permissions),
    ]
