# Generated by Django 2.2 on 2019-06-03 19:30

from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.db import migrations


def set_attr_payment(apps, schema_editor):
    Attribution = apps.get_model("bda", "Attribution")
    for attr in Attribution.objects.all():
        attr.paid = attr.participant.paid
        attr.paymenttype = attr.participant.paymenttype
        attr.save()


def set_participant_payment(apps, schema_editor):
    Participant = apps.get_model("bda", "Participant")
    for part in Participant.objects.all():
        attr_set = part.attribution_set
        part.paid = attr_set.exists() and not attr_set.filter(paid=False).exists()
        try:
            # S'il n'y a qu'un seul type de paiement, on le set
            part.paymenttype = (
                attr_set.values_list("paymenttype", flat=True).distinct().get()
            )
        # Sinon, whatever
        except (ObjectDoesNotExist, MultipleObjectsReturned):
            pass
        part.save()


class Migration(migrations.Migration):

    dependencies = [("bda", "0014_attribution_paid_field")]

    operations = [
        migrations.RunPython(set_attr_payment, set_participant_payment, atomic=True)
    ]
