# Generated by Django 1.11.18 on 2020-05-12 08:58

from django.db import migrations

from authentic2.a2_rbac.models import MANAGE_MEMBERS_OP
from django_rbac.models import CHANGE_OP


def update_self_administration_perm(apps, schema_editor):
    Role = apps.get_model('a2_rbac', 'Role')
    Permission = apps.get_model('a2_rbac', 'Permission')
    Operation = apps.get_model('django_rbac', 'Operation')
    ContentType = apps.get_model('contenttypes', 'ContentType')
    change_op, _ = Operation.objects.get_or_create(slug=str(CHANGE_OP.slug))
    manage_members_op, _ = Operation.objects.get_or_create(slug=str(MANAGE_MEMBERS_OP.slug))
    ct = ContentType.objects.get_for_model(Role)
    perms_to_delete = []
    for role in Role.objects.all():
        try:
            perm = role.permissions.get(operation=change_op, target_ct=ct, target_id=role.pk)
        except Permission.DoesNotExist:
            continue

        new_perm, _ = Permission.objects.get_or_create(
            operation=manage_members_op, target_ct=ct, target_id=role.pk, ou__isnull=True
        )
        role.permissions.add(new_perm)
        role.permissions.remove(perm)
        perms_to_delete.append(perm.pk)
    Permission.objects.filter(pk__in=perms_to_delete, roles__isnull=True).delete()


class Migration(migrations.Migration):

    dependencies = [
        ('a2_rbac', '0023_role_can_manage_members'),
    ]

    operations = [migrations.RunPython(update_self_administration_perm, migrations.RunPython.noop)]
