# Generated by Django 3.2.10 on 2022-01-11 15:09

import json

import dateutil
from django.db import migrations
from i18nfield.strings import LazyI18nString


def to_data(value):
    if value == "True":
        return True
    if value == "False":
        return False
    return value


def get_int(value):
    if value:
        try:
            return int(value)
        except Exception:
            pass


def migrate_data(apps, schema_editor):
    Event = apps.get_model("event", "Event")
    EventSettings = apps.get_model("event", "Event_SettingsStore")
    EventSettings = apps.get_model("event", "Event_SettingsStore")
    PublicVotingSettings = apps.get_model(
        "pretalx_public_voting", "PublicVotingSettings"
    )
    for event in Event.objects.all().filter(plugins__contains="pretalx_public_voting"):
        settings = {
            s.key: s.value
            for s in EventSettings.objects.filter(
                object=event, key__startswith="public_voting_"
            )
        }
        ps, _ = PublicVotingSettings.objects.get_or_create(event=event)
        for key, value in settings.items():
            if key == "public_voting_start":
                ps.start = dateutil.parser.parse(value)
            elif key == "public_voting_end":
                ps.end = dateutil.parser.parse(value)
            elif key == "public_voting_text":
                ps.text = LazyI18nString(json.loads(value))
            elif key == "public_voting_anonymize_speakers":
                ps.anonymize_speakers = to_data(value)
            elif key == "public_voting_show_session_image":
                ps.show_session_image = to_data(value)
            elif key == "public_voting_min_score":
                ps.min_score = get_int(value)
            elif key == "public_voting_max_score":
                ps.max_score = get_int(value)
            elif key.startswith("public_voting_score_name_"):
                score = get_int(key.split("_")[-1])
                ps.score_names[score] = value
        ps.save()


def remove_data(apps, schema_editor):
    PublicVotingSettings = apps.get_model(
        "pretalx_public_voting", "PublicVotingSettings"
    )
    PublicVotingSettings.objects.all().delete()


class Migration(migrations.Migration):
    dependencies = [
        ("pretalx_public_voting", "0002_publicvotingsettings"),
    ]

    operations = [migrations.RunPython(migrate_data, remove_data)]
