# -*- encoding: UTF-8 -*-
"""
Created on 30.09.2011

@author: christian
"""
from django.core.cache import cache

from . import models


def content_menus(request):
    current_page = None
    current_top_page = None
    current_path = request.path_info[1:request.path_info.rfind('.')]

    # erzeuge das Top-Level Menü
    top_menu_items = []
    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')
        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
        top_menu_items.append(item)

    # 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 len(current_path) > 0:
        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_menu_items,
            'current_top_page': current_top_page,
            'current_path': current_path,
            'current_page': current_page
    }
