# Generated by Django 2.1.15 on 2020-01-13 09:22

import sys

from django.db import IntegrityError, migrations, transaction

VIEW_PERMISSION_CODENAMES = {
    'view_aliases': 'view_alias',
    'view_domaliases': 'view_domainalias',
    'view_mailboxes': 'view_mailbox',
}


def rename_view_permissions(apps, schema_editor):
    Permission = apps.get_model('auth', 'Permission')
    db_alias = schema_editor.connection.alias
    # Iterate over permissions and try to rename the codename
    for perm in Permission.objects.using(db_alias).filter(
        codename__in=VIEW_PERMISSION_CODENAMES.keys()
    ):
        codename = perm.codename
        try:
            with transaction.atomic():
                perm.codename = VIEW_PERMISSION_CODENAMES[perm.codename]
                perm.save()
        except IntegrityError:
            print(
                (
                    "Unable to rename '{}' to '{}', a permission with this "
                    "codename already exists.".format(codename, perm.codename)
                ),
                file=sys.stderr,
            )


class Migration(migrations.Migration):

    dependencies = [
        ('admin', '0014_auto_20181017_1628'),
    ]

    operations = [
        migrations.RunPython(rename_view_permissions),
    ]
