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


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.
    configure_log('qirm', opts)

    # 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 = standardize_experiment_child_hierarchy(path_items[2:])
    
    # Delete each specified XNAT object.
    prj = opts.pop('project', qixnat.project())
    with qixnat.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 common XNAT options.
    command.add_options(parser)
    # The input XNAT path.
    parser.add_argument('path', help='the target XNAT object path',
                        metavar='PATH')
    # Parse all arguments.
    args = vars(parser.parse_args())
    # Filter out the empty arguments.
    nonempty_args = dict((k, v) for k, v in args.iteritems() if v != None)

    # Return the path argument and the options.
    return nonempty_args.pop('path'), nonempty_args


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