# Generated by Django 4.0.2 on 2022-02-28 18:54

from django.db import migrations

def do_media_url_split(apps, schema_editor):  # pragma: no cover
    GlobalPreferenceModel = apps.get_model('dynamic_preferences', 'GlobalPreferenceModel')

    # Grab the existing prefs from the DB
    try:
        url_orig = GlobalPreferenceModel.objects.get(section='exordium', name='media_url')
    except GlobalPreferenceModel.DoesNotExist:
        url_orig = None
    try:
        url_html5 = GlobalPreferenceModel.objects.get(section='exordium', name='media_url_html5')
    except GlobalPreferenceModel.DoesNotExist:
        url_html5 = None
    try:
        url_m3u = GlobalPreferenceModel.objects.get(section='exordium', name='media_url_m3u')
    except GlobalPreferenceModel.DoesNotExist:
        url_m3u = None

    if not url_html5 and not url_m3u and url_orig:
        # If we don't have the new prefs but *do* have the orig, copy them over
        # and remove the orig
        url_html5 = GlobalPreferenceModel(
                section='exordium',
                name='media_url_html5',
                raw_value=url_orig.raw_value,
                )
        url_html5.save()
        url_m3u = GlobalPreferenceModel(
                section='exordium',
                name='media_url_m3u',
                raw_value=url_orig.raw_value,
                )
        url_m3u.save()
        url_orig.delete()

    elif url_html5 and url_m3u and url_orig:
        # If we have *all three* of them, just remove the orig.  I suspect this
        # could happen if the site is brought up before migrations have been
        # run, which would populate the new URLs with defaults.  The user may
        # very well have updated the URLs already, too, so deleting the orig
        # is the only sensible thing.
        url_orig.delete()

    else:
        # I think about the only other case possible would be that the app's never
        # been hit (in which case the prefs don't exist in the DB yet, and will be
        # populated by defaults when that happens).  So, do nothing.
        pass

class Migration(migrations.Migration):

    dependencies = [
        ('exordium', '0003_add_opus_support'),
        ('dynamic_preferences', '0006_auto_20191001_2236'),
    ]

    operations = [
        migrations.RunPython(do_media_url_split),
    ]

