# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-07-17 20:11
from __future__ import unicode_literals

from django.db import migrations
from django.contrib.auth.models import Group, Permission
from django.core.management.sql import emit_post_migrate_signal


def add_subject_perms_to_groups(*args, **kwargs):
    # this is to make sure that the permissions created in an earlier migration exist!
    emit_post_migrate_signal(2, False, 'default')

    view_permission = Permission.objects.get(codename='view_subject')
    edit_permission = Permission.objects.get(codename='change_subject')

    osf_admin = Group.objects.get(name='osf_admin')
    read_only = Group.objects.get(name='read_only')

    [osf_admin.permissions.add(perm) for perm in [view_permission, edit_permission]]
    osf_admin.save()

    read_only.permissions.add(view_permission)
    read_only.save()


def remove_subject_perms_from_groups(*args, **kwargs):
    view_permission = Permission.objects.get(codename='view_subject')
    edit_permission = Permission.objects.get(codename='change_subject')

    osf_admin = Group.objects.get(name='osf_admin')
    read_only = Group.objects.get(name='read_only')

    [osf_admin.permissions.remove(perm) for perm in [view_permission, edit_permission]]
    osf_admin.save()

    read_only.permissions.remove(view_permission)
    read_only.save()


class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0044_ever_mentioned_array_to_m2m'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='subject',
            options={'base_manager_name': 'objects', 'permissions': (('view_subject', 'Can view subject details'),)},
        ),
        migrations.RunPython(add_subject_perms_to_groups, remove_subject_perms_from_groups),
    ]
