# Generated by Django 3.2.13 on 2022-05-25 08:39

from django.db import migrations
from django.db.models import Q


def migrate_to_v2(app, schema_editor):
    GlobalSettingsObject_SettingsStore = app.get_model('pretixbase', 'GlobalSettingsObject_SettingsStore')
    EventSettingsStore = app.get_model('pretixbase', 'Event_SettingsStore')
    Event = app.get_model('pretixbase', 'Event')

    # If there are no system-wide OAuth keys set, per-event API keys are used, and we can migrate all events
    if not GlobalSettingsObject_SettingsStore.objects.filter(
            Q(key__in=['payment_paypal_connect_client_id', 'payment_paypal_connect_secret_key'])
            & (Q(value__isnull=True) | ~Q(value=""))
    ).exists():
        for ev in Event.objects.filter(plugins__contains='pretix.plugins.paypal'):
            switch_paypal_version(ev)

    # There are system-wide OAuth keys set - so we need to check each event individually
    else:
        # Only look at events that have the PayPal plugin enabled
        for ev in Event.objects.filter(plugins__contains='pretix.plugins.paypal'):
            # If the payment method is enabled, we don't do anything
            if EventSettingsStore.objects.filter(object_id=ev.pk, key='payment_paypal__enabled', value="True").exists():
                pass
            # In all other cases, the payment method is either disabled or hasn't been set up - in this case we'll
            # migrate the event to v2
            else:
                switch_paypal_version(ev)


def switch_paypal_version(event):
    plugins_active = event.plugins.split(',')

    if 'pretix.plugins.paypal' in plugins_active:
        plugins_active.remove('pretix.plugins.paypal')
        plugins_active.append('pretix.plugins.paypal2')

        event.plugins = ','.join(plugins_active)
        event.save(update_fields=['plugins'])


class Migration(migrations.Migration):

    dependencies = [
        ('paypal', '0002_referencedpaypalobject_payment'),
    ]

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