from collections import namedtuple


def build_rclick_tree(command_p, rclicks=None, top_level=False):
    """
    Return a list of top level RClicks for the button at command_p, which can be
    used later to add the rclick menus.

    After building a list of @rclick children and following siblings of the
    @button this method applies itself recursively to each member of that list
    to handle submenus.

    :Parameters:
    - `command_p`: node containing @button. May be None
    - `rclicks`: list of RClicks to add to, created if needed
    - `top_level`: is this the top level?
    """
    # representation of an rclick node
    RClick = namedtuple('RClick', 'position,children')

    # Called from QtIconBarClass.setCommandForButton.
    if rclicks is None:
        rclicks = list()
    if top_level:
        # command_p will be None for leoSettings.leo and myLeoSettings.leo.
        if command_p:
            if '@others' not in command_p.b:
                rclicks.extend([
                    RClick(position=i.copy(), children=[])
                    # -2 for top level entries, i.e. before "Remove button"
                    for i in command_p.children()
                        if i.h.startswith('@rclick ')
                ])
            for i in command_p.following_siblings():
                if i.h.startswith('@rclick '):
                    rclicks.append(RClick(position=i.copy(), children=[]))
                else:
                    break
        for rc in rclicks:
            build_rclick_tree(rc.position, rc.children, top_level=False)
    else: # recursive mode below top level
        if not command_p:
            return []
        if command_p.b.strip():
            return [] # sub menus can't have body text
        for child in command_p.children():
            # pylint: disable=no-member
            rc = RClick(position=child.copy(), children=[])
            rclicks.append(rc)
            build_rclick_tree(rc.position, rc.children, top_level=False)
    return rclicks