"""
This module provides context processor implementations for gnuviechadmin.

"""
from __future__ import absolute_import

import logging

from django.conf import settings

from gnuviechadmin import __version__ as gvaversion

_LOGGER = logging.getLogger(__name__)


def navigation(request):
    """
    Add navigation items to the request context.

    :param request: Django :py:class:`HttpRequest <django.http.HttpRequest>`
    :return: new context items
    :rtype: dict

    """
    if request.headers.get("x-requested-with") == "XMLHttpRequest":
        return {}
    context = {
        "webmail_url": settings.GVA_LINK_WEBMAIL,
        "phpmyadmin_url": settings.GVA_LINK_PHPMYADMIN,
        "phppgadmin_url": settings.GVA_LINK_PHPPGADMIN,
        "active_item": "dashboard",
    }
    if request.resolver_match:
        viewfunc = request.resolver_match.func
        viewmodule = viewfunc.__module__
        if viewmodule == "contact_form.views":
            context["active_item"] = "contact"
        elif viewmodule in (
            "hostingpackages.views",
            "osusers.views",
            "userdbs.views",
            "managemails.views",
            "websites.views",
            "domains.views",
        ):
            context["active_item"] = "hostingpackage"
        elif viewmodule in ("allauth.account.views", "allauth.socialaccount.views"):
            context["active_item"] = "account"
        elif viewmodule == "django.contrib.flatpages.views" and request.path.endswith(
            "/impressum/"
        ):
            context["active_item"] = "imprint"
        elif not viewmodule.startswith("django.contrib.admin"):
            _LOGGER.debug(
                "no special handling for view %s in module %s, fallback to "
                "default active menu item %s",
                viewfunc.__name__,
                viewmodule,
                context["active_item"],
            )
    return context


def version_info(request):
    """
    Context processor that adds the gnuviechadmin version to the request
    context.

    """
    context = {
        "gnuviechadmin_version": gvaversion,
    }
    return context
