# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-11-20 08:20
from __future__ import unicode_literals


from django.db import migrations
from django.db.models import F, OuterRef, Subquery


def correct_activity_transition_date(apps, schema_editor):
    Contribution = apps.get_model('activities', 'Contribution')
    Activity = apps.get_model('activities', 'Activity')
    Donation = apps.get_model('funding', 'Donation')
    ContentType = apps.get_model('contenttypes', 'ContentType')

    donation_ctype = ContentType.objects.get_for_model(Donation)

    transition_date = Activity.objects.filter(
        id=OuterRef('activity_id')
    ).values_list(
        'transition_date'
    )[:1]
    # Donations should use date created
    Contribution.objects.filter(polymorphic_ctype=donation_ctype).update(transition_date=F('created'))
    # For tasks & events rely on activity transition_date
    Contribution.objects.exclude(polymorphic_ctype=donation_ctype).update(transition_date=Subquery(transition_date))


class Migration(migrations.Migration):

    dependencies = [
        ('activities', '0012_auto_20191108_1317'),
        ('funding', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(correct_activity_transition_date,
                             migrations.RunPython.noop)
    ]
