import token


def decompose_name(node):
    """
    NOTE: Per the lib2to3 grammar:
            dotted_name: NAME ('.' NAME)*
          This means that dotted_name can be either dotted or not dotted, i.e. it's a generalized
          form of NAME. So this function will cover both cases.

    Given a dotted_name node this will return a tuple of the form (pkg, name, full_string) where
    all are str
        ex: a.b.c => (a.b, c, a.b.c)
            b.c => (b, c, b.c)
            c => (None, c, c)
    otherwise it will return None for each field
    """
    if node.type == token.NAME:
        # node is just a name, no dots
        return '', node.value, node.value

    if node.children:
        # Right most node will be the name, i.e. a.b.c = ['a','.','b','.','c']
        name_node = node.children[-1]
        package_nodes = node.children[:-2]
        name = str(name_node).strip()
        package = ''.join(str(n).strip() for n in package_nodes)
        full = ''.join(str(n).strip() for n in node.children)
        return package, name, full

    return None, None, None