# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2020-02-12 09:25
from __future__ import unicode_literals

from django.db import migrations, connection

from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant

from django.contrib.auth.models import Permission, Group


def remove_anonymous_permissions(apps, schema_editor):
    permissions = (
        ('assignments', 'api_read_assignment'),
        ('events', 'api_read_event'),
        ('activities', 'api_read_activity'),
        ('funding', 'api_read_funding'),
    )

    tenant = Client.objects.get(schema_name=connection.tenant.schema_name)

    with LocalTenant(tenant):
        if properties.CLOSED_SITE:
            anonymous = Group.objects.get(name='Anonymous')

            for (app, codename) in permissions:
                permission = Permission.objects.get(
                    content_type__app_label=app,
                    codename=codename
                )

                anonymous.permissions.remove(permission)

            anonymous.save()


class Migration(migrations.Migration):

    dependencies = [
        ('activities', '0017_auto_20200205_1054'),
    ]

    operations = [
        migrations.RunPython(remove_anonymous_permissions)
    ]

# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2020-02-12 09:25
from __future__ import unicode_literals

from django.db import migrations, connection

from bluebottle.clients import properties
from bluebottle.clients.models import Client
from bluebottle.clients.utils import LocalTenant

from django.contrib.auth.models import Permission, Group


def remove_anonymous_permissions(apps, schema_editor):
    permissions = (
        ('assignments', 'api_read_assignment'),
        ('events', 'api_read_event'),
        ('activities', 'api_read_activity'),
        ('funding', 'api_read_funding'),
    )

    tenant = Client.objects.get(schema_name=connection.tenant.schema_name)

    with LocalTenant(tenant):
        if properties.CLOSED_SITE:
            anonymous = Group.objects.get(name='Anonymous')

            for (app, codename) in permissions:
                try:
                    permission = Permission.objects.get(
                        content_type__app_label=app,
                        codename=codename
                    )

                    anonymous.permissions.remove(permission)
                except Permission.DoesNotExist:
                    pass
            anonymous.save()


class Migration(migrations.Migration):

    dependencies = [
        ('activities', '0017_auto_20200205_1054'),
    ]

    operations = [
        migrations.RunPython(remove_anonymous_permissions)
    ]

Fix migration for new tenants
Fix migration for new tenants
