# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-21 15:44
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations


def migrate_ldap_group_data_forward(apps, schema_editor):
    # We need to split group_dn into ldap_model and group_name
    # First, lets create a mapping from base_dn to ldap model
    base_dn_map = {
        g["BASE_DN"].lower(): g["MODEL_NAME"] for g in settings.JASMIN_SERVICES["LDAP_GROUPS"]
    }
    Behaviour = apps.get_model("jasmin_services", "LdapGroupBehaviour")
    for behaviour in Behaviour.objects.all():
        cn_part, base_dn = behaviour.group_dn.split(",", 1)
        behaviour.ldap_model = base_dn_map[base_dn.lower()]
        behaviour.group_name = cn_part.split("=", 1)[1]
        behaviour.save()


def migrate_ldap_group_data_reverse(apps, schema_editor):
    # Migrate from ldap_model and group_name to group_dn
    base_dn_map = {g["MODEL_NAME"]: g["BASE_DN"] for g in settings.JASMIN_SERVICES["LDAP_GROUPS"]}
    Behaviour = apps.get_model("jasmin_services", "LdapGroupBehaviour")
    for behaviour in Behaviour.objects.all():
        behaviour.group_dn = "cn={},{}".format(
            behaviour.group_name, base_dn_map[behaviour.ldap_model]
        )
        behaviour.save()


class Migration(migrations.Migration):
    dependencies = [
        ("jasmin_services", "0003_add_ldap_model_fields"),
    ]

    operations = [
        migrations.RunPython(migrate_ldap_group_data_forward, migrate_ldap_group_data_reverse),
    ]
