# Generated by Finn Stutzenstein on 2019-03-01 10:02

from django.db import migrations


def set_reference_projector(apps, schema_editor):
    """
    Sets all references to one projector. Tries to get the id from the former
    config value. If there is no config or the id is invalid, the first projector
    will be taken
    """
    ConfigStore = apps.get_model("core", "ConfigStore")
    Projector = apps.get_model("core", "Projector")

    try:
        config = ConfigStore.objects.get(
            key="projector_currentListOfSpeakers_reference"
        )
        reference_id = config.value
        config.delete()  # cleanup. this config is not needed anymore
        reference_projector = Projector.objects.get(pk=reference_id)
    except (ConfigStore.DoesNotExist, Projector.DoesNotExist):
        reference_projector = Projector.objects.first()

    for projector in Projector.objects.all():
        projector.reference_projector = reference_projector
        projector.save(skip_autoupdate=True)


class Migration(migrations.Migration):

    dependencies = [("core", "0019_countdown_title_2")]

    operations = [migrations.RunPython(set_reference_projector)]
