# SPDX-FileCopyrightText: 2023-present Tobias Kunze
# SPDX-License-Identifier: AGPL-3.0-only WITH LicenseRef-Pretalx-AGPL-3.0-Terms

# Generated by Django 4.2.4 on 2023-09-17 09:01

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


def replace_wrong_values(locale_string):
    return (
        locale_string.replace("zh-TW", "zh-Hant")
        .replace("zh-CN", "zh-Hans")
        .replace("zh-tw", "zh-hant")
        .replace("zh-cn", "zh-hans")
    )


def fix_locale_codes(apps, schema_editor):
    Event = apps.get_model("event", "Event")
    for event in Event.objects.filter(
        Q(locale_array__contains="zh")
        | Q(content_locale_array__contains="zh")
        | Q(locale__contains="zh")
    ):
        for attr in ["locale", "locale_array", "content_locale_array"]:
            setattr(event, attr, replace_wrong_values(getattr(event, attr)))
        event.save()

    User = apps.get_model("person", "User")
    for user in User.objects.filter(locale__contains="zh"):
        user.locale = replace_wrong_values(user.locale)
        user.save()


class Migration(migrations.Migration):
    dependencies = [
        ("event", "0032_alter_event_timezone"),
    ]

    operations = [
        migrations.RunPython(
            fix_locale_codes,
            migrations.RunPython.noop,  # Fixing a bug, so we're not reverting
        ),
    ]
