"""
$URL: svn+ssh://svn.mems-exchange.org/repos/trunk/dulcinea/lib/ui/directory.py $
$Id: directory.py 28089 2006-03-24 19:58:23Z rmasse $
"""
from dulcinea.common import get_request, get_response, get_path, get_user
from dulcinea.common import not_found, redirect
from dulcinea.ui.util import index_page
from qp.fill.directory import get_directory_path


class DynamicExportingDirectory (object):

    def get_exports(self):
        return []

    def _q_translate(self, component):
        """(component : string) -> string | None
        """
        for export, name, crumb, title in self.get_exports():
            if component == export:
                return name
        return None

    def _q_lookup(self, component):
        """(component : string) -> object

        Lookup a path component and return the corresponding object (usually
        a Directory, a method or a string).  Returning None signals that the
        component does not exist.
        """
        return None

    def _q_traverse(self, path):
        """(path: [string]) -> object

        Traverse a path and return the result.
        """
        component = path[0]
        name = self._q_translate(component)
        if name is None:
            obj = self._q_lookup(component)
        else:
            obj = getattr(self, name)
        if obj is None:
            print '\n404: %r has no component %r; PATH=%s; USER=%s' % (
                self, name, get_path(), get_user())
            not_found()
        if path[1:]:
            if hasattr(obj, '_q_traverse'):
                result = obj._q_traverse(path[1:])
            else:
                not_found()
        elif callable(obj):
            result = obj()
        else:
            result = obj
        if result is None:
            not_found()
        else:
            return result

    def __call__(self):
        if (self._q_translate('') is not None and
            not get_request().get_fields()):
            # Fix missing trailing slash.
            return redirect(get_path() + "/", permanent=True)
        else:
            return None

    def _q_index(self):
        return index_page(self)


def get_path_directory_list():
    app_root = get_request().get_environ('SCRIPT_NAME', '')
    path = get_path()
    path_components = path[len(app_root):].split('/')
    namespace_stack = get_directory_path()
    if get_response().get_status_code() == 200:
        offset = -1
    else:
        offset = 0
    return [('./' + '../' * (len(namespace_stack) - k + offset),
             namespace_stack[k])
            for k in range(min(len(path_components), len(namespace_stack)))]

def gen_crumb_tree_menu_items(path, directory):
    for component, name, crumb, title in directory.get_exports():
        if crumb: # skip crumbs and menus if no crumb
            css_class = 'menu_' + component.replace('.', '_')
            yield (path + component, crumb, title, css_class)

def get_crumb_tree():
    """() - > [[(path:str, crumb:str, title:str, css_class:str)]]
    Each list in the result is a menu of exports for a directory on the
    current path with a derived css class name for each menu entry.
    """
    crumb_tree = []
    for path, directory in get_path_directory_list():
        menu = list(gen_crumb_tree_menu_items(path, directory))
        if menu:
            crumb_tree.append(menu)
    return crumb_tree
