# -*- coding: utf-8 -*-
from django.conf import settings
from django.urls import path, reverse
from django.utils.html import escape
from django.utils.translation import gettext as _

from wagtail import hooks
from wagtail.admin.menu import AdminOnlyMenuItem, MenuItem
from wagtail.rich_text import LinkHandler
from wagtail.rich_text.pages import PageLinkHandler as BasePageLinkHandler

from ocyan.main.loading import get_ocyan_class

from .middleware import get_current_request, get_current_site

UserReportView = get_ocyan_class("ocyan_plugin_wagtail.user_views", "UserReportView")
account_chooser_viewset = get_ocyan_class(
    "ocyan_plugin_wagtail.viewsets", "account_chooser_viewset"
)


@hooks.register("insert_global_admin_css")
def global_admin_css():
    # This makes sure that the stats on the wagtai homepage aren't 100% hight.
    # Though not bad, it is highly irritable when clicking in an empty spot on the page.
    return "<style>.summary ul.stats a { !important; height: auto !important; }</style>"


# pylint: disable=abstract-method
class TargetBlankLinkHandler(LinkHandler):
    identifier = "external"

    @classmethod
    def expand_db_attributes(cls, attrs):
        href = attrs["href"]
        return '<a href="%s" target="_blank" rel="noopener noreferrer">' % escape(href)


class PageLinkHandler(BasePageLinkHandler):
    @classmethod
    def expand_db_attributes_many(cls, attrs_list: list[dict]) -> list[str]:
        """
        Until https://github.com/joeyjurjens/wagtail/pull/1/files (hopefully) gets merged into wagtail.
        """

        def get_url(page):
            request = get_current_request()
            site = get_current_site()
            if request or site:
                return page.get_url(request=request, current_site=site)
            return page.localized.url

        return [
            '<a href="%s">' % escape(get_url(page)) if page else "<a>"
            for page in cls.get_many(attrs_list)
        ]


# Patch the original wagtail one with our own.
BasePageLinkHandler.expand_db_attributes_many = (
    PageLinkHandler.expand_db_attributes_many
)


@hooks.register("register_rich_text_features")
def register_target_blank_external_link(features):
    # Defaults to False, but can be overidden on project level.
    if settings.OPEN_EXTERNAL_RICHTEXT_LINKS_IN_NEW_WINDOW:
        features.register_link_type(TargetBlankLinkHandler)


@hooks.register("register_admin_menu_item")
def register_view_site_menuitem():
    return MenuItem(label=_("View site"), url="/", icon_name="home", order=0)


@hooks.register("register_icons")
def register_icons(icons):
    return icons + [
        "wagtailadmin/icons/icon-list.svg",
        "wagtailadmin/icons/icon-shopping-cart.svg",
        "wagtailadmin/icons/icon-sitemap.svg",
        "wagtailadmin/icons/icon-users.svg",
        "wagtailadmin/icons/icon-bullhorn.svg",
        "wagtailadmin/icons/icon-chart-bar.svg",
    ]


@hooks.register("register_reports_menu_item")
def register_user_report_menu_item():
    return AdminOnlyMenuItem(
        _("Users"),
        reverse("user_report"),
        icon_name=UserReportView.header_icon,
        order=700,
    )


@hooks.register("register_admin_urls")
def register_report_urls():
    return [
        path("reports/user/", UserReportView.as_view(), name="user_report"),
    ]


@hooks.register("register_admin_viewset")
def register_viewset():
    return account_chooser_viewset
