# Generated by Django 2.2.20 on 2021-04-15 07:48

from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations

from turkle.models import Batch, Project

User = get_user_model()


def add_turkle_user_admin_group(apps, schema_editor):
    """Create custom group that has CRU (but not D) access to User/Group models
    """

    # Force Django to create permissions before all migrations are run
    #
    # When running the migrations creates the database tables from
    # scratch (such as when running 'python manage.py test', but not
    # when running 'python manage.py migrate' to update an existing
    # database), Django will not add database rows with permissions
    # for the User and Group models until *after* all migrations have
    # been run.  We need these rows with permission data to be added
    # to the database now, so that we can grant the permissions to the
    # new Group instance we are creating.
    #
    # This is a known issue with Django that was identified in Django
    # bug #23422, "Cannot add Permission to Group in data migration"
    # back in 2014:
    #   https://code.djangoproject.com/ticket/23422
    #
    # The bug report was closed as "wontfix" in 2014.  The use of
    # emit_post_migrate_signal() - which supposedly works in Django
    # 2.2+ - was suggested in a comment on the bug report made on
    # 2020-05-07:
    #   https://code.djangoproject.com/ticket/23422#comment:28
    emit_post_migrate_signal(1, False, 'default')

    batch_ctype = ContentType.objects.get_for_model(Batch)
    group_ctype = ContentType.objects.get_for_model(Group)
    project_ctype = ContentType.objects.get_for_model(Project)
    user_ctype = ContentType.objects.get_for_model(User)

    batch_perms = [Permission.objects.get(codename='view_batch', content_type=batch_ctype)]
    group_perms = [Permission.objects.get(codename=codename, content_type=group_ctype)
                   for codename in ['add_group', 'change_group', 'view_group']]
    project_perms = [Permission.objects.get(codename='view_project', content_type=project_ctype)]
    user_perms = [Permission.objects.get(codename=codename, content_type=user_ctype)
                  for codename in ['add_user', 'change_user', 'view_user']]

    # Because we use get_or_create(), if an existing Turkle installation already
    # has a "Turkle User Admin" group, we will overwrite the existing permissions.
    (uag, _) = Group.objects.get_or_create(name='Turkle User Admin')
    uag.permissions.set(batch_perms + group_perms + project_perms + user_perms)


class Migration(migrations.Migration):

    dependencies = [
        ('turkle', '0010_project_allotted_assignment_time'),
    ]

    operations = [
        migrations.RunPython(add_turkle_user_admin_group),
    ]
