# Generated by Django 2.0.3 on 2018-04-16 10:34

from django.db import migrations


def migrate(apps, schema_editor):
    Organization = apps.get_model('admin', 'Organization')
    Unit = apps.get_model('admin', 'Unit')
    Scope = apps.get_model('admin', 'Scope')
    for i, scope in enumerate([Organization, Unit]):
        for cls in scope.__subclasses__():
            for obj in cls.objects.all():
                pk = obj.pk + (1000 * i)
                Scope.objects.get_or_create(pk=pk)
                scope_lookup = {'id': obj.pk}
                scope_update = {'id': pk}
                scope.objects.filter(**scope_lookup).update(**scope_update)
                cls_lookup = {'{}_ptr_id'.format(scope.__name__.lower()): obj.pk}
                cls_update = {'{}_ptr_id'.format(scope.__name__.lower()): pk}
                cls.objects.filter(**cls_lookup).update(**cls_update)
                for rel in cls._meta.related_objects:
                    if rel.remote_field.model._meta.app_label == 'admin':
                        continue
                    lookup = {rel.remote_field.name: obj.pk}
                    update = {rel.remote_field.name: pk}
                    rel.remote_field.model.objects.filter(**lookup).update(**update)


class Migration(migrations.Migration):

    dependencies = [
        ('admin', '0002_scope'),
    ]

    operations = [migrations.RunPython(migrate)]
