"""
open/DurusWorks/qp/fill/durus_directory.qpy

"""
from durus.persistent import PersistentObject
from qp.fill.directory import Directory
from qp.fill.html import href, div
from qp.pub.common import get_publisher, page
from qp.lib.spec import persistent_vars

class DurusDirectory(Directory):
    """
    A Directory for browsing the Durus Database.
    Notice that there is no access control provided here.
    Applications should not allow traversal into an instance
    of this class unless the user is allowed to see everything
    in the database.
    """
    def __init__(self, obj=None):
        self.obj = obj

    def get_exports(self):
        yield ('', '_q_index', self.get_object().__class__.__name__, None)

    def get_object(self):
        if self.obj is None:
            self.obj = get_publisher().get_root()
        return self.obj

    def _q_index:xml(self):
        self.display(self.get_object())

    def _q_lookup(self, component):
        try:
            return self.__class__(
                get_publisher().get_connection().get(int(component)))
        except ValueError:
            return None

    def display:xml(self, obj):
        def format:xml(value):
            if isinstance(value, PersistentObject):
                href(value._p_format_durus_id() + '/', repr(value))
            elif isinstance(value, list):
                '['
                ', '.join([format(v) for v in value])
                ']'
            elif isinstance(value, tuple):
                '('
                ', '.join([format(v) for v in value])
                ')'
            elif isinstance(value, dict):
                '<div style="margin-left:2em">'
                '{'
                for k, v in value.items():
                    '<div>'
                    format(k)
                    ' : '
                    format(v)
                    '</div>'
                '}'
                '</div>'
            else:
                repr(value)

        page("Object: %s" % obj._p_format_durus_id(),
             div(str(obj), style="font-weight:bold"),
             format(persistent_vars(obj)))
