from django import template

from wagtail.admin.search import admin_search_areas
from wagtail.admin.ui import sidebar

try:
    # Wagtail 8.0+
    from wagtail.admin.telepath import JSContext
except ImportError:
    # Wagtail 7.x and earlier
    from wagtail.telepath import JSContext

from ocyan.core.fender import config

register = template.Library()


@register.simple_tag(takes_context=True)
def wagtailadmin_adapter_media(context):
    if config.i18n_enabled:
        request = context["request"]
        search_areas = admin_search_areas.search_items_for_request(request)
        if search_areas:
            search_area = search_areas[0]
        else:
            search_area = None

        search_module = sidebar.SearchModule(search_area) if search_area else None

        js_ctx = JSContext()
        js_ctx.pack(search_module)
        return js_ctx.media

    return ""
