#!/usr/bin/env python
"""
Deletes an OHSU QIN XNAT object.
"""
import os
import sys
import imp
import argparse
from qiutil import command


class SessionNotFoundError(Exception):
    pass


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

    # Configure the logger.
    command.configure_log('qirm', opts)

    # Import the pyxnat and qiutil pipeline module after configuring
    # the logger.
    from pyxnat.core.resources import Reconstruction
    import qiutil
    from qiutil import qixnat

    # Parse the XNAT hierarchy argument.
    path_items = path_str.split('/')
    if len(path_items) < 2:
        raise ValueError("The search path must include at least three items,"
                         " e.g. Breast003/Session01")
    sbj, sess = path_items[0:2]
    child_path = qixnat.helpers.standardize_experiment_child_hierarchy(path_items[2:])
    
    # Delete each specified XNAT object.
    prj = opts.pop('project', qiutil.project())
    with qixnat.connection.connect(config) as xnat:
        sess_obj = xnat.get_session(prj, sbj, sess)
        if not xnat.exists(sess_obj):
            raise SessionNotFoundError("No such XNAT session: %s %s %s" %
                                       (prj, sbj, sess))
        for child in xnat.expand_child_hierarchy(sess_obj, child_path):
            if child.exists():
                child.delete()
    
    return 0


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

    # The log options.
    command.add_log_options(parser)

    # The input XNAT path.
    parser.add_argument('path', help='the target XNAT object path',
                        metavar='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())
