from django import forms
from django.conf import settings
from django.urls import reverse
from django.utils.functional import cached_property
from django.utils.translation import get_language
from django.utils.translation import gettext as _

from wagtail.admin.staticfiles import versioned_static

# pylint: disable=unused-import
from wagtail.admin.telepath import Adapter, register
from wagtail.admin.ui.sidebar import PageExplorerMenuItem, SearchModule

from ocyan.core.fender import config


class SidebarSearchWithLanguageChooserAdapter(Adapter):
    js_constructor = "ocyan.sidebar.SearchWithLanguageChooserModule"

    def js_args(self, obj):
        meta = {
            "strings": {
                "SEARCH": _("Search"),
            }
        }

        return [
            obj.search_area.url,
            reverse("set_language"),
            get_language(),
            settings.LANGUAGES,
            meta,
        ]

    @cached_property
    def media(self):
        return forms.Media(
            js=[
                versioned_static("wagtailadmin/ocyanwagtailadmin.js"),
            ]
        )


class ProperlyNavigatingPageExplorerMenuItem(Adapter):
    js_constructor = "ocyan.sidebar.ProperlyNavigatingPageExplorerMenuItem"

    def js_args(self, obj):
        return [
            {
                "url": obj.url,
                "name": obj.name,
                "label": obj.label,
                "icon_name": obj.icon_name,
                "classname": obj.classname,
            },
            obj.start_page_id,
            get_language(),
            settings.LANGUAGE_CODE,
            settings.LANGUAGES,
        ]


if config.i18n_enabled:
    register(SidebarSearchWithLanguageChooserAdapter(), SearchModule)
    register(ProperlyNavigatingPageExplorerMenuItem(), PageExplorerMenuItem)
