# Generated by Django 3.2.15 on 2022-12-23 14:41

from django.db import migrations


def set_channel_permissions(apps, schema_editor):
    ActivityChannelRelation = apps.get_model(
        "activities", "ActivityChannelRelation"
    )
    ContentType = apps.get_model("contenttypes", "ContentType")
    UserObjectPermission = apps.get_model("guardian", "UserObjectPermission")
    Permission = apps.get_model("auth", "Permission")
    Channel = apps.get_model("chats", "Channel")

    channel_ct = ContentType.objects.get_for_model(Channel)

    permissions = []
    for codename in [
        "view_channel",
        "change_channel",
        "delete_channel",
        "start_thread",
        "post_comment",
    ]:
        try:
            permissions.append(
                Permission.objects.get(
                    codename=codename, content_type=channel_ct
                )
            )
        except Permission.DoesNotExist:
            pass

    for relation in ActivityChannelRelation.objects.filter(
        symbolic_relation=False
    ):
        for leader in relation.activity.leaders.filter(user__isnull=False):
            for permission in permissions:
                UserObjectPermission.objects.get_or_create(
                    permission=permission,
                    content_type=channel_ct,
                    object_pk=relation.channel.pk,
                    user=leader.user,
                )


class Migration(migrations.Migration):

    dependencies = [
        (
            "chats",
            "0006_channelmaterialrelation_unique_channel_relation_for_material",
        ),
        (
            "activities",
            "0017_activitymaterialrelation_unique_activity_relation_for_material",
        ),
    ]

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