# Generated by Django 2.2.6 on 2019-10-09 21:35

from django.db import migrations
from django.db.models import Case, When, F, Value, Sum, IntegerField

# This migration has to be separate from 0002 so that it can be in a separate
# transaction


def add_losers(apps, schema_editor):
    Match = apps.get_model("core", "Match")
    for match in (
        Match.objects.annotate(
            tmp_loser=Case(
                When(winner=F("playermatch__player"), then=Value(0)),
                default=F("playermatch__player"),
                output_field=IntegerField(),
            )
        )
        .values("id")
        .annotate(loser_id=Sum("tmp_loser"))
        .values("id", "loser_id")
    ):
        Match.objects.filter(id=match["id"]).update(loser_id=match["loser_id"])


def remove_losers(apps, schema_editor):
    Match = apps.get_model("core", "Match")
    Match.objects.update(loser_id=1)


class Migration(migrations.Migration):

    dependencies = [("core", "0002_match_loser")]

    operations = [migrations.RunPython(add_losers, remove_losers)]
