# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2018-09-05 19:27
from __future__ import unicode_literals

from django.db import migrations


def add_tmp_party(apps, schema_editor):
    Organzation = apps.get_model("popolo", "Organization")
    ResultEvent = apps.get_model("results", "ResultEvent")
    Party = apps.get_model("parties", "Party")

    parties_by_legacy_slug = {}
    org_id_to_party_slug = {}

    for party in Party.objects.all():
        parties_by_legacy_slug[party.legacy_slug] = party

    org_qs = Organzation.objects.filter(classification="Party").select_related(
        "extra"
    )
    for org in org_qs:
        org_id_to_party_slug[org.pk] = org.extra.slug

    for org_id, party_slug in org_id_to_party_slug.items():
        qs = ResultEvent.objects.filter(winner_party_id=org_id)
        if qs.exists():
            qs.update(winner_party_tmp=parties_by_legacy_slug[party_slug])

    if ResultEvent.objects.filter(winner_party_tmp=None).exists():
        print(ResultEvent.objects.filter(winner_party_tmp=None))
        raise ValueError("ReusltEvent objects without tmp winner party found")


class Migration(migrations.Migration):

    dependencies = [
        ("results", "0022_resultevent_winner_party_tmp"),
        ("parties", "0008_unique_ec_id"),
    ]

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