# Generated by Django 4.2.3 on 2023-10-04 13:23
from django.db import migrations
from guardian.shortcuts import assign_perm

def create_group(apps, circle, field_name, permissions):
    Group = apps.get_model("auth", "Group")
    Permission = apps.get_model("auth", "Permission")
    GroupObjectPermission = apps.get_model("guardian", "GroupObjectPermission")
    ContentType = apps.get_model("contenttypes", "ContentType")
    group = Group.objects.create(name=f'LDP_{circle._meta.model_name}_{field_name}_{circle.id}')
    setattr(circle, field_name, group)
    for perm_name in permissions:
        ctype = ContentType.objects.get(model='circle')
        permission = Permission.objects.get(content_type=ctype, codename=f'{perm_name}_circle')
        GroupObjectPermission.objects.get_or_create(permission=permission, group=group, content_type=ctype, object_pk=circle.pk)


def migrate_groups(apps, schema_editor):
    '''copies the members and admins of the circles into new groups'''
    Circle = apps.get_model("djangoldp_circle", "Circle")
    for circle in Circle.objects.all():
        create_group(apps, circle, 'members', ['view'])
        create_group(apps, circle, 'admins', ['view', 'change', 'control'])

        for member in circle.oldmembers.all():
            circle.members.user_set.add(member.user)
            if member.is_admin:
                circle.admins.user_set.add(member.user)
        circle.save()

def reverse_migrate_groups(apps, schema_editor):
    '''copies the members of the circles into the old member model'''
    Circle = apps.get_model("djangoldp_circle", "Circle")
    CircleMember = apps.get_model("djangoldp_circle", "CircleMember")
    for circle in Circle.objects.all():
        if circle.members:
            for user in circle.members.user_set.all():
                if not CircleMember.objects.filter(user=user, circle=circle).exists():
                    is_admin = user in circle.admins.user_set.all()
                    CircleMember.objects.create(user=user, circle=circle, is_admin=is_admin)
            circle.members.delete()
        if circle.admins:
            circle.admins.delete()


def migrate_status(apps, schema_editor):
    '''copies the status of the circles into the public flag'''
    Circle = apps.get_model("djangoldp_circle", "Circle")
    for circle in Circle.objects.all():
        if circle.status == 'Public':
            circle.public = True
            circle.save()

def reverse_migrate_status(apps, schema_editor):
    '''copies the status of the circles into the public flag'''
    Circle = apps.get_model("djangoldp_circle", "Circle")
    for circle in Circle.objects.all():
        circle.status == 'Public' if circle.public else 'Private'

def migrate_communities(apps, schema_editor):
    '''copies the communities from the intermediary model into the inner field'''
    CommunityCircle = apps.get_model("djangoldp_community", "CommunityCircle")
    for communitycircle in CommunityCircle.objects.all():
        communitycircle.circle.community = communitycircle.community
        communitycircle.circle.save()

def reverse_migrate_communities(apps, schema_editor):
    '''copies the communities from the inner field into the intermediary model'''
    Circle = apps.get_model("djangoldp_circle", "Circle")
    CommunityCircle = apps.get_model("djangoldp_community", "CommunityCircle")
    for circle in Circle.objects.all():
        if circle.community:
            circle.oldcommunity, created = CommunityCircle.objects.get_or_create(circle=circle, community=circle.community)
            circle.save()


class Migration(migrations.Migration):
    dependencies = [
        ('djangoldp_circle', '0036_alter_circle_options_alter_circlemember_options_and_more'),
    ]

    operations = [
        migrations.RunPython(migrate_status, reverse_migrate_status),
        migrations.RunPython(migrate_groups, reverse_migrate_groups),
        migrations.RunPython(migrate_communities, reverse_migrate_communities),
    ]