from zope.security.management import getInteraction

from zope.app import zapi
from zope.app.component.hooks import getSite

from zope.app.publisher.browser.menu import BrowserMenu
from zope.app.publisher.browser.menu import BrowserMenuItem, BrowserSubMenuItem

from documentlibrary.core import interfaces

class Menu(BrowserMenu):

    def getMenuItems(self, object, request):
        base_url = zapi.absoluteURL(getSite(), request)
        items = super(Menu, self).getMenuItems(object, request)
        for item in items:
            if item['action'].startswith('/'):
                # XXX this is not a real solution, but works for now...
                item['action'] = '%s%s' % (base_url, item['action'])

        return items

class MainMenu(Menu):
    def getMenuItems(self, object, request):
        items = super(MainMenu, self).getMenuItems(object, request)
        # add help url
        help_url = zapi.getUtility(interfaces.ICustomText).help_url
        if help_url:
            items.append({
                'title': u'help',
                'description': u'help',
                'action': zapi.getUtility(interfaces.ICustomText).help_url,
                'selected': '',
                'icon': u'',
                'extra': u'',
                'submenu': [],
                })
        return items
    
class CategoryMenu(BrowserMenu):

    def getMenuItems(self, object, request):
        categories = getSite()['categories']
        return self._items(categories, object, request)

    def _items(self, item, object, request):
        interaction = getInteraction()
        result = []
        for subitem in item.values():
            if not interfaces.ICategory.providedBy(subitem):
                continue
            if interaction.checkPermission(
                'documentlibrary.ApproveDocument', subitem):
                title = subitem.name
                description = subitem.name
                url = zapi.absoluteURL(subitem, request)
                if object is subitem:
                    selected = 'selected'
                else:
                    selected = ''
            else:
                title = subitem.name
                description = subitem.name
                url = None
                selected = ''
            item = {
                'title': title,
                'description': description,
                'action': url,
                'selected': selected,
                'icon': u'',
                'extra': u'',
                'submenu': self._items(subitem, object, request)}
            result.append(item)
        return cleanup(result)
    
def cleanup(to_clean):
    """Clean up invisible part from menu structure.
    """
    result = []
    for item in to_clean:
        r = item_cleanup(item)
        if r is not None:
            result.append(r)
    return result

def item_cleanup(item):
    if empty(item):
        return None
    result = {}
    result.update(item)
    result['submenu'] = sub = []
    for entry in item['submenu']:
        r = item_cleanup(entry)
        if r is None:
            continue
        sub.append(r)
    return result
    
def empty(item):
    """Return true if menu structure is entirely empty.
    """
    if item['action'] is not None:
        return False
    for entry in item['submenu']:
        if not empty(entry):
            return False
    return True

    
        
