# Generated by Django 2.2.24 on 2021-11-03 08:02

from django.db import migrations


def get_embedvideo_permissions(apps):
    # return a queryset of the 'add_embedvideo' and 'change_embedvideo' permissions
    Permission = apps.get_model("auth.Permission")
    ContentType = apps.get_model("contenttypes.ContentType")

    embedvideo_content_type, _created = ContentType.objects.get_or_create(
        model="embedvideo",
        app_label="wagtail_embed_videos",
    )
    return Permission.objects.filter(
        content_type=embedvideo_content_type, codename__in=["add_embedvideo", "change_embedvideo"]
    )


def copy_embedvideo_permissions_to_collections(apps, schema_editor):
    Collection = apps.get_model("wagtailcore.Collection")
    Group = apps.get_model("auth.Group")
    GroupCollectionPermission = apps.get_model("wagtailcore.GroupCollectionPermission")

    root_collection = Collection.objects.get(depth=1)

    for permission in get_embedvideo_permissions(apps):
        for group in Group.objects.filter(permissions=permission):
            GroupCollectionPermission.objects.create(group=group, collection=root_collection, permission=permission)


def remove_embedvideo_permissions_from_collections(apps, schema_editor):
    GroupCollectionPermission = apps.get_model("wagtailcore.GroupCollectionPermission")
    embedvideo_permissions = get_embedvideo_permissions(apps)

    GroupCollectionPermission.objects.filter(permission__in=embedvideo_permissions).delete()


class Migration(migrations.Migration):

    dependencies = [
        ("wagtail_embed_videos", "0004_auto_20211103_0746"),
    ]

    operations = [
        migrations.RunPython(
            copy_embedvideo_permissions_to_collections, remove_embedvideo_permissions_from_collections
        ),
    ]
