#!/usr/bin/python

# Copyright (c) 2011 Christian Haselgrove
# BSD License: http://www.opensource.org/licenses/bsd-license.php

import sys
import os
import json
import xml.dom.minidom

base_xml_template = """<?xml version="1.0" encoding="UTF-8"?>
<!-- generated by generate_sample_xml -->
<%s xmlns:%s="%s" xmlns:xnat="http://nrg.wustl.edu/xnat" ID="">
<xnat:subject_ID>xnat_S123456</xnat:subject_ID>
</%s>
"""

progname = os.path.basename(sys.argv[0])

if len(sys.argv) == 1:
    print
    print 'usage: %s <JSON file>' % progname
    print
    print 'outputs sample XML for a custom XNAT data type'
    print
    sys.exit(1)

try:
    fo = open(sys.argv[1])
except Exception, data:
    sys.stderr.write('%s: %s\n' % (progname, str(data)))
    sys.exit(1)

data = json.load(fo)
(ns, ns_uri) = data['namespace']

root_tag_name = '%s:%s' % (ns, data['name'])

base_xml = base_xml_template % (root_tag_name, ns, ns_uri, root_tag_name)
doc = xml.dom.minidom.parseString(base_xml)
root_node = doc.getElementsByTagName(root_tag_name)[0]

for element in data['elements']:
    xml_el = doc.createElement(element['name'])
    if element['type'] == 'xs:integer':
        text_node = doc.createTextNode('1')
        xml_el.appendChild(text_node)
        root_node.appendChild(xml_el)
    else:
        fmt = '%s: unknown or unhandled type %s\n'
        sys.stderr.write(fmt % (progname, element['type']))
        sys.exit(1)

print doc.toxml()

sys.exit(0)

# eof
