# Generated by Django 2.2.7 on 2019-11-19 23:14
from django.db import migrations

from cms.api import add_plugin
from cms.models import StaticPlaceholder


def migrate_footer_to_static_placeholder(apps, schema_editor):
    """
    Create a footer with the new static placeholder from the existing footer pages that were
    placed under the "annex" page and displayed in the footer via a `show_menu_below_id`
    template tag.
    """
    Page = apps.get_model("cms", "Page")
    Title = apps.get_model("cms", "Title")

    # We should import StaticPlaceholder from apps but its `draft` and `public` fields
    # are custom foreign key field that checks that they are targeting an instance of
    # `cms.models.Placeholder` so the code would not work. We can safely assume that the
    # Placeholder and StaticPlaceholder models are still there when this migration is run
    static_placeholder, was_created = StaticPlaceholder.objects.get_or_create(
        code="footer"
    )

    if not was_created:
        # If the static placeholder was already existing, it means this migration is being
        # replayed and we better do nothing.
        return

    for is_draft in [False, True]:
        # Look for an existing footer page
        try:
            footer_page = Page.objects.get(
                reverse_id="annex", publisher_is_draft=is_draft
            )
        except Page.DoesNotExist:
            return

        placeholder = (
            static_placeholder.draft if is_draft else static_placeholder.public
        )

        for language in Title.objects.filter(page=footer_page).values_list(
            "language", flat=True
        ):
            # Create the <ul> section to carry the list of links
            section = add_plugin(
                placeholder,
                plugin_type="SectionPlugin",
                language=language,
                template="richie/section/section_list.html",
            )

            # Create a <li> link for each page in the exiting footer menu
            for page in Page.objects.filter(
                node__parent=footer_page.node,
                in_navigation=True,
                title_set__language=language,
                publisher_is_draft=is_draft,
            ):
                title = page.title_set.get(language=language)
                add_plugin(
                    placeholder,
                    plugin_type="LinkPlugin",
                    language=language,
                    internal_link_id=page.id,
                    name=title.title,
                    target=section,
                )


class Migration(migrations.Migration):

    dependencies = [
        ("courses", "0009_auto_20191014_1801"),
        ("section", "0003_auto_20191119_1650"),
    ]

    operations = [
        migrations.RunPython(
            migrate_footer_to_static_placeholder, migrations.RunPython.noop
        )
    ]
