from xml.dom import minidom
import os
rv = minidom.parse('/stage/source/paraview/trunk/Remoting/Views/Resources/views_and_representations.xml')
nodes = {}
repTypes = set()
[repTypes.add(x) for x in ('ChartRepresentationProxy', 'RepresentationProxy', 'SpreadSheetRepresentationProxy', 'PVMoleculeRepresentationProxy', 'PVRepresentationProxy')]
# Also 'Extension', 'Proxy', '#comment', '#text'
nn = 0
for node in rv.childNodes[0].childNodes:
    if node.nodeName != 'ProxyGroup':
        continue
    pgtype = node.getAttribute('name')
    if pgtype != 'representations' and pgtype != 'internal_representations':
        continue
    # OK, we have a proxy group holding representations of one sort or another.
    for proxy in node.childNodes:
        pxtype = proxy.nodeName
        if pxtype not in repTypes:
            continue
        # key = (proxy.parentNode.getAttribute('name'), proxy.getAttribute('name'), pxtype)
        key = (proxy.parentNode.getAttribute('name'), proxy.getAttribute('name'))
        nodes[key] = proxy
        nn += 1
assert(nn == len(nodes))

print("""digraph "representations" {
  stylesheet="representation_graph.css"
""")
# Declare nodes:
for key in nodes:
    print('  ', (key[0] + '_' + key[1]), ' [label="%s", class="%s"]' % (key[1], nodes[key].nodeName))
# Declare inheritance arcs:
print('  subgraph "inheritance" {')
for key in nodes:
    node = nodes[key]
    if node.hasAttribute('base_proxygroup') and node.hasAttribute('base_proxyname'):
        base = node.getAttribute('base_proxygroup') + '_' + node.getAttribute('base_proxyname')
        print('    ', (key[0] + '_' + key[1]), ' -> ', base, ' [class="inheritance"]')
print('  }')
# Declare subproxy arcs:
print('  subgraph "subproxy" {')
allSubs = set()
for key in nodes:
    node = nodes[key]
    for subproxy in node.childNodes:
        if subproxy.nodeName != 'SubProxy':
            continue
        for spn in subproxy.childNodes:
            if spn.nodeName != 'Proxy':
                continue
            if spn.hasAttribute('proxygroup') and spn.hasAttribute('proxyname'):
                childKey = (spn.getAttribute('proxygroup'), spn.getAttribute('proxyname'))
                child = spn.getAttribute('proxygroup') + '_' + spn.getAttribute('proxyname')
                if childKey in nodes:
                    print('    ', (key[0] + '_' + key[1]), ' -> ', child, ' [class="subproxy"]')
                else:
                    allSubs.add(child)
print('  }')
print("""}""")

# rps = rv.getElementsByTagName('RepresentationProxy')
# prps = rv.getElementsByTagName('PVRepresentationProxy')
#
# nodes = {}
# for rp in rps:
#     key = (rp.parentNode.getAttribute('name'), rp.getAttribute('name'))
#     nodes[key] = rp
#     print(key)
# for prp in prps:
#     key = (prp.parentNode.getAttribute('name'), prp.getAttribute('name'))
#     nodes[key] = prp
#     print(key)
