""" Django contextprocessor to have dynamicly generated menus in the templates.
"""
from django.core.cache import cache

from . import models


def content_menus(request):
    """ Generate the menu tree and add these info to the template context.

    The following variables will be added to the template context:
    - top_menu_items: QuerySet with all top level pages (children of the root)
    - current_top_page: Page Object of the top level page that is currently
      shown to the user, or it's childen are shown to the user.
    - current_path: the path part of the current URL,
    - current_page: the current Page object that is associated with this URL

    :param request: a Django request object
    :return: a dict with the template variables mentioned above
    """
    current_page = None
    current_top_page = None
    current_path = request.path_info[1:request.path_info.rfind('.')]

    # erzeuge das Top-Level Menü
    top_level_pages = cache.get('top_level_pages')
    if top_level_pages is None:
        top_level_pages = models.Page.objects.filter(parent=None)
        top_level_pages = top_level_pages.exclude(slug='index')
        top_level_pages = top_level_pages.order_by('position')
        top_level_pages = top_level_pages.prefetch_related('subpages')
        cache.set('top_level_pages', top_level_pages, 360)
    for item in top_level_pages:
        if current_path.startswith(item.path):
            item.active = True
            current_top_page = item
        else:
            item.active = False

    # Entdecke die aktuell geöffnete Seite
    all_pages = cache.get('all_pages')
    if all_pages is None:
        all_pages = models.Page.objects.values_list('path', 'id')
        all_pages = dict((path, page_id) for path, page_id in all_pages)
        cache.set('all_pages', all_pages, 360)

    while current_path:
        if current_path in all_pages:
            current_page = models.Page.objects.get(pk=all_pages[current_path])
            break
        current_path = current_path[0:current_path.rfind('.')]

    return {'top_menu_items': top_level_pages,
            'current_top_page': current_top_page,
            'current_path': current_path,
            'current_page': current_page}
