# pylint: disable=unused-argument

from django.db import migrations


def initialize_wagtail_locales(apps, schema_editor):
    Language = apps.get_model("wagtailtrans", "Language")
    TranslatablePage = apps.get_model("wagtailtrans", "TranslatablePage")
    Locale = apps.get_model("wagtailcore", "Locale")

    language_map = {}
    for lang in Language.objects.all():
        locale, _ = Locale.objects.get_or_create(language_code=lang.code)
        language_map[lang.code] = locale

    # select all the canonical pages
    for page in TranslatablePage.objects.filter(
        language_id__isnull=False, canonical_page_id__isnull=True
    ):
        if page.language.code != page.locale.language_code:
            page.locale = language_map[page.language.code]
            page.save()

        locales = set([page.locale.language_code])

        translations = TranslatablePage.objects.filter(canonical_page=page)
        for translation in translations:
            translation.locale = language_map[translation.language.code]
            if translation.language.code not in locales:
                translation.translation_key = page.translation_key
                locales.add(translation.language.code)
                translation.translation_key = page.translation_key

            translation.save()


def neutralize_translatable_siteroot(apps, schema_editor):
    Page = apps.get_model("wagtailcore", "Page")
    I18nSiteRootPage = apps.get_model("i18n", "I18nSiteRootPage")
    ContentType = apps.get_model("contenttypes", "ContentType")
    TranslatablePage = apps.get_model("wagtailtrans", "TranslatablePage")

    siteroots = I18nSiteRootPage.objects.all()
    for siteroot in siteroots:
        homepage = TranslatablePage.objects.filter(
            path__startswith=siteroot.path,
            depth=siteroot.depth + 1,
            canonical_page_id__isnull=True,
        ).first()
        siteroot.sites_rooted_here.update(root_page=homepage)

    siteroots.update(content_type=ContentType.objects.get_for_model(Page))


class Migration(migrations.Migration):
    dependencies = [
        ("ocyan_plugin_wagtail", "0026_merge_0005_rename_page_ptr_0025_menulink"),
    ]

    operations = [
        migrations.RunPython(initialize_wagtail_locales, migrations.RunPython.noop),
        migrations.RunPython(
            neutralize_translatable_siteroot, migrations.RunPython.noop
        ),
    ]
