from django.db import migrations


def rename_permissions(apps, schema_editor):
    Permission = apps.get_model('auth', 'Permission')
    ContentType = apps.get_model('contenttypes', 'ContentType')

    try:
        ct = ContentType.objects.get(app_label='base', model='accessright')
    except ContentType.DoesNotExist:
        # db from scratch: contenttypes are created on post_migrate signal
        return

    if not Permission.objects.filter(content_type=ct, codename='see_accessright').exists():
        # old schema, rename view_accessright permission
        p = Permission.objects.get(content_type=ct, codename='view_accessright')
        p.codename = 'see_accessright'
        p.name = 'Can see access right'
        p.save()

    ct = ContentType.objects.get(app_label='base', model='resourcelog')
    if not Permission.objects.filter(content_type=ct, codename='see_resourcelog').exists():
        # old schema, rename view_resourcelog permission
        p = Permission.objects.get(content_type=ct, codename='view_resourcelog')
        p.codename = 'see_resourcelog'
        p.name = 'Can see resource log'
        p.save()


class Migration(migrations.Migration):

    dependencies = [
        ('base', '0027_transaction_id'),
    ]

    operations = [
        migrations.RunPython(rename_permissions, reverse_code=migrations.RunPython.noop),
    ]
