# Generated by Django 3.1.2 on 2020-11-20 12:05

from django.contrib.auth.management import create_permissions
from django.db import migrations


def migrate_permissions(apps, schema_editor):
    """
    Ensure model permissions have been created
    """
    for app_config in apps.get_app_configs():
        app_config.models_module = True
        create_permissions(app_config, apps=apps, verbosity=0)
        app_config.models_module = None


def assign_permissions(apps, schema_editor):
    Permission = apps.get_model("auth", "Permission")
    Group = apps.get_model("auth", "Group")

    add_ea_permission = Permission.objects.get(codename="add_economicassessment")
    change_ea_permission = Permission.objects.get(codename="change_economicassessment")
    archive_ea_permission = Permission.objects.get(
        codename="archive_economicassessment"
    )
    approve_ea_permission = Permission.objects.get(
        codename="approve_economicassessment"
    )

    add_eia_permission = Permission.objects.get(codename="add_economicimpactassessment")
    change_eia_permission = Permission.objects.get(
        codename="change_economicimpactassessment"
    )
    archive_eia_permission = Permission.objects.get(
        codename="archive_economicimpactassessment"
    )

    analyst_group = Group.objects.get(name="Analyst")
    analyst_group.permissions.add(
        add_ea_permission,
        change_ea_permission,
        archive_ea_permission,
        approve_ea_permission,
        add_eia_permission,
        change_eia_permission,
        archive_eia_permission,
    )

    administrator_group = Group.objects.get(name="Administrator")
    administrator_group.permissions.add(
        add_ea_permission,
        change_ea_permission,
        archive_ea_permission,
        approve_ea_permission,
        add_eia_permission,
        change_eia_permission,
        archive_eia_permission,
    )


class Migration(migrations.Migration):

    dependencies = [
        ("user", "0018_auto_20201105_1239"),
    ]

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