# Generated by Django 4.2.9 on 2024-11-07 20:53

from django.db import migrations

def set_representative_from_fixed_masked(apps, cats):
    # get all duplicated events
    DuplicatedEvents = apps.get_model("agenda_culturel", "DuplicatedEvents")
    duplicated = DuplicatedEvents.objects.all().prefetch_related('event_set')

    to_update = []
    for d in duplicated:
        # there is no representative
        d.representative = None
        # except if d is fixed
        if d.fixed:
            # and if there is at least one non masked (should be the case)
            e_not_masked = [e for e in d.event_set.all() if not e.masked]
            # keep the first one
            if len(e_not_masked) >= 1:
                d.representative = e_not_masked[0]
        to_update.append(d)        

    DuplicatedEvents.objects.bulk_update(to_update, fields=["representative"])

def set_fixed_masked_from_representative(apps, cats):
    Event = apps.get_model("agenda_culturel", "Event")
    events = Event.objects.all().prefetch_related("possibly_duplicated")

    to_update = []
    for e in events:
        if not e.possibly_duplicated:
            e.masked = False
        else:
            e.masked = e.possibly_duplicated.representative and e.possibly_duplicated.representative == e            
        to_update.append(e)
    
    Event.objects.bulk_update(to_update, fields=["masked"])

    # get all duplicated events
    DuplicatedEvents = apps.get_model("agenda_culturel", "DuplicatedEvents")
    duplicated = DuplicatedEvents.objects.all().prefetch_related('event_set')

    # for each event
    to_update = []
    for d in duplicated:
        d.fixed = not d.representative is None
        to_update.append(d)
    
    DuplicatedEvents.objects.bulk_update(to_update, fields=["fixed"])

class Migration(migrations.Migration):

    dependencies = [
        ('agenda_culturel', '0102_duplicatedevents_representative'),
    ]

    operations = [
        migrations.RunPython(set_representative_from_fixed_masked, reverse_code=set_fixed_masked_from_representative),
    ]
