from bazbase.dependencies import Dependencies

# TODO(xavid): This is super-dumb.  See fixing inheritance to not use this.
PARENT_DOT_THIS = '<<parent.this />>'
def is_parent_dot_this(s):
    return PARENT_DOT_THIS == s

def nice_value(propval):
    deps = Dependencies()
    #with benchmarking("rendering nice value for %s" % propval):
    if True:
        e = propval.element
        anc = e.get_ancestors()
        pv = propval
        propname = propval.propname
        deps.addDep(pv)
        deps.addParentDep(e)
        while (anc and is_parent_dot_this(pv.value)):
            e = anc.pop()
            try:
                pv = e.get_propval(propname)
            except KeyError, exc:
                deps.addNoPropvalDep(e.ename, propname)
                return exc.args[0], deps
            deps.addDep(pv)
            deps.addParentDep(e)
        ret = unicode(pv.value, 'utf-8').strip()

        ds = '<<default>>'
        de = '<</default>>'
        if ret.startswith(ds) and ret.endswith(de):
            ret = ret[len(ds):-len(de)]
        return ret, deps

def as_tree(elms):
    """Formats elms as a tree.

    elms should be a list of elements ordered preorder, such that each element
    is followed by a single region of its descendants, but with missing
    elements allowed.
    The return value is a list of roots.  A node is either a leaf
    or a subtree.
    A leaf is [element].  A subtree is [element, [<>], [<>]]."""
    ret = []
    stack = [ret]
    while len(elms) > 0:
        e = elms.pop(0)
        while len(stack) > 1 and not stack[-1][0].is_ancestor_of(e):
            stack.pop()
        bubble = [e]
        stack[-1].append(bubble)
        stack.append(bubble)
    return ret
