import re

from django.conf import settings
from django.contrib.postgres.lookups import Unaccent
from django.db.models.functions import Lower
from django.templatetags.static import static
from django.utils.html import format_html
from django.utils.safestring import mark_safe
from wagtail import hooks
from wagtail.admin.ui.components import Component


class WelcomePanel(Component):
    order = 1000

    def render_html(self, parent_context):
        return mark_safe(
            """
        <section class="nice-padding">
          <div class="help-block help-info">
            <p>Nevíte si rady? Nápovědu naleznete na <a href="https://majak.pirati.cz/">majak.pirati.cz</a></p>
          </div>
        </section>
        """
        )


@hooks.register("construct_homepage_panels")
def add_another_welcome_panel(request, panels):
    panels.append(WelcomePanel())


@hooks.register("construct_explorer_page_queryset")
def show_my_profile_only(parent_page, pages, request):
    requested_html = re.search(r"^text/html", request.META.get("HTTP_ACCEPT"))
    if not requested_html:
        return pages.order_by(Unaccent(Lower("title")))
    return pages


@hooks.register("insert_global_admin_css")
def global_admin_css():
    style = format_html(
        '<link rel="stylesheet" href="{}">', static("majak/wagtail/theme.css")
    )

    if settings.MAJAK_ENV == "test":
        style += '<style type="text/css">.sidebar__inner { background-color: #00203A }</style>'
    if settings.MAJAK_ENV == "dev":
        style += '<style type="text/css">.sidebar__inner { background-color: #002A20 }</style>'

    return mark_safe(style)


# TODO - Style add button based on whether or not there are blocks already added.
#        This is surprisingly complicated.
# @hooks.register('insert_global_admin_js')
# def global_admin_js():
#     return format_html(
#         '<script src="{}"></script>',
#         static('majak/wagtail/theme.js')
#     )