# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-05-03 14:47
from __future__ import unicode_literals

from django.db import migrations
from django.contrib.auth.models import Permission
from osf.models import OSFUser

# Old permission groups
add_preprintservice = Permission.objects.get(codename='add_preprintservice')
change_preprintservice = Permission.objects.get(codename='change_preprintservice')
delete_preprintservice = Permission.objects.get(codename='delete_preprintservice')
view_preprintservice = Permission.objects.get(codename='view_preprintservice')

# New permission groups
add_preprint = Permission.objects.get(codename='add_preprint')
change_preprint = Permission.objects.get(codename='change_preprint')
delete_preprint = Permission.objects.get(codename='delete_preprint')
osf_admin_view_preprint = Permission.objects.get(codename='osf_admin_view_preprint')

def unmigrate_preprint_service_permissions(state, schema):
    remove_users_from_permission(add_preprint)
    remove_users_from_permission(change_preprint)
    remove_users_from_permission(delete_preprint)
    remove_users_from_permission(osf_admin_view_preprint)

def remove_users_from_permission(perm):
    for user in OSFUser.objects.filter(user_permissions=perm):
        u.user_permissions.remove(perm)

def add_users_to_renamed_permission(old_perm, new_perm):
    for user in OSFUser.objects.filter(user_permissions=old_perm):
        user.user_permissions.add(new_perm)

def migrate_preprint_service_permissions(state, schema):
    add_users_to_renamed_permission(add_preprintservice, add_preprint)
    add_users_to_renamed_permission(change_preprintservice, change_preprint)
    add_users_to_renamed_permission(delete_preprintservice, delete_preprint)
    add_users_to_renamed_permission(view_preprintservice, osf_admin_view_preprint)

class Migration(migrations.Migration):

    dependencies = [
        ('osf', '0096_preprint_node_divorce'),
    ]

    operations = [
        migrations.RunPython(migrate_preprint_service_permissions, unmigrate_preprint_service_permissions),
    ]

Add a data migration for adding the users from the old preprintservice permissions to the newly named preprint permissions.