# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-10-20 13:40
from __future__ import unicode_literals

from django.db import migrations

from course_discovery.apps.publisher.constants import (INTERNAL_USER_GROUP_NAME, PARTNER_COORDINATOR_GROUP_NAME,
                                                       PUBLISHER_GROUP_NAME, REVIEWER_GROUP_NAME)
GROUPS = [INTERNAL_USER_GROUP_NAME, PARTNER_COORDINATOR_GROUP_NAME, REVIEWER_GROUP_NAME, PUBLISHER_GROUP_NAME]


def add_people_permission(apps, schema_editor):
    Permission = apps.get_model('auth', 'Permission')
    OrganizationExtension = apps.get_model('publisher', 'OrganizationExtension')
    Group = apps.get_model('auth', 'Group')

    target_permissions = Permission.objects.filter(
        codename__in=['add_person', 'change_person', 'delete_person']
    )

    for org in OrganizationExtension.objects.all():
        org.group.permissions.add(*target_permissions)

    # Also add the permissions to publisher role groups
    publisher_groups = Group.objects.filter(name__in=GROUPS)
    for group in publisher_groups:
        group.permissions.add(*target_permissions)


def remove_people_permission(apps, schema_editor):
    Permission = apps.get_model('auth', 'Permission')
    OrganizationExtension = apps.get_model('publisher', 'OrganizationExtension')
    Group = apps.get_model('auth', 'Group')

    target_permissions = Permission.objects.filter(
        codename__in=['add_person', 'change_person', 'delete_person']
    )

    for org in OrganizationExtension.objects.all():
        org.group.permissions.remove(*target_permissions)

    # Also remove the permissions to publisher role groups
    publisher_groups = Group.objects.filter(name__in=GROUPS)
    for group in publisher_groups:
        group.permissions.remove(*target_permissions)


class Migration(migrations.Migration):

    dependencies = [
        ('publisher', '0060_auto_20171004_0521'),
    ]

    operations = [
        migrations.RunPython(add_people_permission, remove_people_permission),
    ]
