# Generated by Django 3.1.1 on 2020-09-15 19:19

from django.apps.registry import Apps
from django.db import migrations


def create_default_property_mappings(apps: Apps, schema_editor):
    LDAPPropertyMapping = apps.get_model("passbook_sources_ldap", "LDAPPropertyMapping")
    db_alias = schema_editor.connection.alias
    mapping = {
        "name": "name",
        "first_name": "givenName",
        "last_name": "sn",
        "email": "mail",
    }
    for object_field, ldap_field in mapping.items():
        expression = f"return ldap.get('{ldap_field}')"
        LDAPPropertyMapping.objects.using(db_alias).get_or_create(
            expression=expression,
            object_field=object_field,
            defaults={
                "name": f"Autogenerated LDAP Mapping: {ldap_field} -> {object_field}"
            },
        )
    ad_mapping = {
        "username": "sAMAccountName",
        "attributes.upn": "userPrincipalName",
    }
    for object_field, ldap_field in ad_mapping.items():
        expression = f"return ldap.get('{ldap_field}')"
        LDAPPropertyMapping.objects.using(db_alias).get_or_create(
            expression=expression,
            object_field=object_field,
            defaults={
                "name": f"Autogenerated Active Directory Mapping: {ldap_field} -> {object_field}"
            },
        )


class Migration(migrations.Migration):

    dependencies = [
        ("passbook_sources_ldap", "0005_auto_20200913_1947"),
    ]

    operations = [
        migrations.RunPython(create_default_property_mappings),
    ]