#!/usr/bin/env python
"""
Lists XNAT objects.
"""
import sys
import os
import argparse
from qiutil.command import configure_log
import qixnat
from qixnat import command
from qixnat.helpers import xnat_path
from qixnat.facade import ChildNotFoundError

def main(argv=sys.argv):
    # Parse the command line arguments.
    path, opts = _parse_arguments()
    # The XNAT configuration.
    config = opts.pop('config', None)
    # Configure the logger.
    configure_log('qils', opts)

    # Print the XNAT object names specified by the path. 
    with qixnat.connect(config) as xnat:
        try:
            for child in xnat.expand_path(path):
                print xnat_path(child)
        except ChildNotFoundError:
            print ("No such XNAT object: %s" % path)
            return 1

    return 0


def _parse_arguments():
    """Parses the command line arguments."""
    parser = argparse.ArgumentParser()

    # The log options.
    qixnat.command.add_options(parser)

    # The input XNAT hierarchy path.
    parser.add_argument('path', help='the target XNAT object path')

    args = vars(parser.parse_args())
    nonempty_args = dict((k, v) for k, v in args.iteritems() if v != None)

    return nonempty_args.pop('path'), nonempty_args


if __name__ == '__main__':
    sys.exit(main())
