# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-02-02 12:18
from __future__ import unicode_literals

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


def delete_old_comment_permission(apps, schema_editor):
    """
    Deletes the old 'can_see_and_manage_comments' permission which is
    split up into two seperate permissions.
    """
    perm = Permission.objects.filter(codename='can_see_and_manage_comments')

    if len(perm):
        perm = perm.get()
        # Save content_type for manual creation of new permissions.
        content_type = perm.content_type

        # Save groups. list() is necessary to evaluate the database query right now.
        groups = list(perm.group_set.all())

        # Delete permission
        perm.delete()

        # Create new permission
        perm_see = Permission.objects.create(
            codename='can_see_comments',
            name='Can see comments',
            content_type=content_type)
        perm_manage = Permission.objects.create(
            codename='can_manage_comments',
            name='Can manage comments',
            content_type=content_type)

        for group in groups:
            group.permissions.add(perm_see)
            group.permissions.add(perm_manage)
            group.save()


class Migration(migrations.Migration):

    dependencies = [
        ('motions', '0004_motionchangerecommendation_other_description'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='motion',
            options={
                'default_permissions': (),
                'ordering': ('identifier',),
                'permissions': (
                    ('can_see', 'Can see motions'),
                    ('can_create', 'Can create motions'),
                    ('can_support', 'Can support motions'),
                    ('can_see_comments', 'Can see comments'),
                    ('can_manage_comments', 'Can manage comments'),
                    ('can_manage', 'Can manage motions')
                ),
                'verbose_name': 'Motion'
            },
        ),
        migrations.RunPython(
            delete_old_comment_permission
        ),
    ]
