# -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2017-05-20 02:58
from __future__ import unicode_literals
import logging

from django.db import migrations


logger = logging.getLogger(__file__)


def fix_bad_participating_organisations(apps, *args):
    iati_ActivityParticipatingOrganisation = apps.get_model('iati', 'ActivityParticipatingOrganisation')
    aims_ActivityParticipatingOrganisation = apps.get_model('aims', 'ActivityParticipatingOrganisation')

    orphan_iati_apos = iati_ActivityParticipatingOrganisation.objects.filter(local_data=None)
    logger.info('Fixing {} orphan iati.ActivityParticipatingOrganisation'.format(orphan_iati_apos.count()))

    for iati_apo in orphan_iati_apos:
        serialized_apo = iati_apo.__dict__
        del serialized_apo['_state']
        aims_ActivityParticipatingOrganisation.objects.create(remote_data_id=iati_apo.pk, **serialized_apo)

    assert iati_ActivityParticipatingOrganisation.objects.count() == aims_ActivityParticipatingOrganisation.objects.count()


class Migration(migrations.Migration):

    dependencies = [
        ('aims', '0027_auto_20170517_1618'),
    ]

    operations = [
        # migrations.RunPython(fix_bad_participating_organisations, reverse_code=migrations.RunPython.noop),
    ]
