# Generated by Django 2.2.13 on 2020-06-12 08:15
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db import migrations

from emeis.core.utils import rebuild_mptt_model


def create_admin(apps, schema_editor):
    try:
        admin_username = settings.ADMIN_USERNAME
        admin_role_slug = settings.ADMIN_ROLE_SLUG
        admin_scope_name = settings.ADMIN_SCOPE_NAME
    except AttributeError:
        raise ImproperlyConfigured(
            (
                "You must set 'ADMIN_USERNAME', 'ADMIN_ROLE_SLUG' and "
                "'ADMIN_SCOPE_NAME' in your settings."
            )
        )

    admin_email = None
    if settings.ADMINS:
        admin_email = settings.ADMINS[0][1]

    User = apps.get_model("emeis_core", "User")
    Role = apps.get_model("emeis_core", "Role")
    Acl = apps.get_model("emeis_core", "Acl")
    Scope = apps.get_model("emeis_core", "Scope")

    admin_user = User.objects.create(username=admin_username, email=admin_email)
    admin_role = Role.objects.create(slug=admin_role_slug)

    # arbitrary values for required mptt-attributes. `rebuild_mptt_model` will fix them
    admin_scope = Scope.objects.create(
        name=admin_scope_name, lft=0, level=0, rght=0, tree_id=0
    )
    rebuild_mptt_model(Scope)

    Acl.objects.create(user=admin_user, scope=admin_scope, role=admin_role)


class Migration(migrations.Migration):

    dependencies = [
        ("emeis_core", "0001_initial"),
    ]

    operations = [
        migrations.RunPython(create_admin, migrations.RunPython.noop),
    ]
