
import sys
# peoplelib was generated from people_9.xsd
import peoplelib


def parse(inFilename):
    doc = peoplelib.parsexml_(inFilename)
    rootNode = doc.getroot()
    rootTag, rootClass = peoplelib.get_root_tag(rootNode)
    if rootClass is None:
        rootTag = 'people'
        rootClass = supermod.people
    rootObj = rootClass.factory()
    rootObj.build(rootNode)
    # Enable Python to collect the space used by the DOM.
    doc = None
##     sys.stdout.write('<?xml version="1.0" ?>\n')
##     rootObj.export(sys.stdout, 0, name_=rootTag,
##         namespacedef_='xmlns:pl="http://kuhlman.com/people.xsd"')
    return rootObj


def test(inFilename):
    root = parse(inFilename)
    person_list = root.get_person()
    person_count = len(person_list)
    print 'There are %d people in this document.' % (person_count, )
    show_person(person_list)
    # Change the name of the 2nd person.
    person1 = person_list[1]
    person1.set_name('Shankar')
    person1.add_interest('XML')
    person1.add_interest('XML Schema')
    # Create a new person.
    # Look at the __init__() method to see the signature of the constructor.
    person = peoplelib.person(name="Dave")
    # Since the "person" child is defined with maxOccurs="unbounded",
    #   there is an add_person() method.
    person.add_interest('birding')
    person.add_interest('photography')
    person.add_interest('Python')
    root.add_person(person)
    print '*' * 50
    show_person(person_list)


def show_person(person_list):
    for person in person_list:
        name = person.get_name()
        if name is not None:
            print '-' * 20
            print 'The name of this person is %s.' % (name, )
            interest = person.get_interest()
            # interest is defined with maxOccurs="unbounded".
            # Any child with maxOccurs greater than 1 or unbounded is 
            #   represented by a list.  So we format the list with "and"
            #   between items in the list.
            interest = ' and '.join(interest)
            print '%s in interested in %s.' % (name, interest, )
            agents = person.get_agent()
            for agent in agents:
                firstname = agent.get_firstname()
                print '    %s is the agent of %s.' % (firstname, name, )


def main():
    args = sys.argv[1:]
    if len(args) != 1:
        print 'Usage: python test.py doc_file_name'
        sys.exit(1)
    inFilename = args[0]
    test(inFilename)


if __name__ == '__main__':
    #import pdb; pdb.set_trace()
    main()

