# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-15 12:24
from __future__ import unicode_literals

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


class Migration(migrations.Migration):

    dependencies = [
        ('orgs', '0021_auto_20180315_0823'),
    ]

    def populate_rapidpro_config(apps, schema_editor):
        Org = apps.get_model("orgs", "Org")
        orgs = Org.objects.all()

        for org in orgs:
            if not org.config:
                continue

            backends_config_dict = getattr(settings, 'DATA_API_BACKENDS_CONFIG', {})
            for backend_slug in backends_config_dict:
                config_fields = getattr(settings, 'BACKENDS_ORG_CONFIG_FIELDS', [])
                for config_field in config_fields:
                    name = config_field['name']
                    existing_value = org.config['common'].get(name, None)
                    if backend_slug not in org.config:
                        org.config[backend_slug] = dict()
                    org.config[backend_slug][name] = existing_value

            org.save()

    def noop(apps, schema_editor):
        pass
    
    operations = [
        migrations.RunPython(populate_rapidpro_config, noop)
    ]
