# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-24 20:46
from __future__ import unicode_literals

from django.db import migrations

def migrate_field_references(apps, schema_editor):
    """This is an irreversible migration"""
    CustomField = apps.get_model('data', 'CustomField')
    CustomFieldIntegration = apps.get_model('data', 'CustomFieldIntegration')
    CustomData = apps.get_model('data', 'CustomData')
    APIIntegration = apps.get_model('data', 'APIIntegration')

    default_integration = APIIntegration.objects.create(source='self')
    for field in CustomField.objects.all():
        field_integration = CustomFieldIntegration.objects.create(
            field=field, integration=default_integration,
            account=field.account, owner=field.owner
        )
    CustomData.objects.all().delete()

def migrate_data_sources(apps, schema_editor):
    """This is an irreversible migration"""
    APIIntegration = apps.get_model('data', 'APIIntegration')
    APIIntegrationSource = apps.get_model('data', 'APIIntegrationSource')
    DataSource = apps.get_model('data', 'DataSource')

    for data_source in DataSource.objects.all():
        integration, _ = APIIntegration.objects.update_or_create(
            source=data_source.source,
            defaults={
                'source_display': data_source.source_display,
                'source_icon': data_source.source_icon,
            }
        )
        APIIntegrationSource.objects.update_or_create(
            integration=integration,
            model=data_source.model,
            field=data_source.field,
            defaults={
                'model_display': data_source.model_display,
                'model_icon': data_source.model_icon,
                'field_display': data_source.field_display,
                'field_icon': data_source.field_icon,
            }
        )

class Migration(migrations.Migration):

    dependencies = [
        ('data', '0020_schema_auto_20170524_2005'),
    ]

    operations = [
        migrations.RunPython(migrate_field_references),
        migrations.RunPython(migrate_data_sources),
    ]
