from django.contrib.admin.utils import quote
from django.templatetags.static import static
from django.urls import reverse
from django.utils.html import format_html
from wagtail import hooks
from wagtail.admin.menu import MenuItem

from associations.models import AssociationIndex
from events.models import EventIndex
from news.models import NewsIndex


@hooks.register("register_rich_text_features")
def enable_additional_rich_text_features(features):
    features.default_features.extend(["h5", "h6", "blockquote"])


@hooks.register("register_admin_menu_item")
def register_events_menu_item():
    page = EventIndex.objects.first()
    events_url = "#"
    if page:
        events_url = reverse("wagtailadmin_explore", args=(quote(page.pk),))
    return MenuItem("Arrangementer", events_url, icon_name="date", order=1)


@hooks.register("register_admin_menu_item")
def register_associations_menu_item():
    page = AssociationIndex.objects.first()
    associations_url = "#"
    if page:
        associations_url = reverse("wagtailadmin_explore", args=(quote(page.pk),))
    return MenuItem("Foreninger", associations_url, icon_name="group", order=2)


@hooks.register("register_admin_menu_item")
def register_associations_menu_item():
    page = NewsIndex.objects.first()
    news_url = "#"
    if page:
        news_url = reverse("wagtailadmin_explore", args=(quote(page.pk),))
    return MenuItem("Nyheter", news_url, icon_name="info-circle", order=3)


@hooks.register("construct_page_action_menu")
def make_publish_default_action(menu_items, request, context):
    for index, item in enumerate(menu_items):
        if item.name == "action-publish":
            menu_items.pop(index)
            menu_items.insert(0, item)
            break


@hooks.register("insert_editor_js")
def editor_js():
    return format_html('<script src="{}"></script>', static("js/page-editor.js"))
