#!/usr/bin/env python
"""
Deletes a XNAT object.
"""
import sys
import os
import re
import argparse
from qiutil.command import configure_log
import qixnat
from qixnat import command

class UnsupportedError(Exception):
    pass


def main(argv=sys.argv):
    # Parse the command line arguments.
    paths, opts = _parse_arguments()
    # The XNAT configuration.
    config = opts.pop('config', None)
    # Configure the logger.
    configure_log('qirm', opts)
    
    # Validate that file objects are not specified, since
    # pyxnat file object delete is a no-op.
    for path in paths:
        if re.search('/files?(/\w+)?$', path):
            raise UnsupportedError("XNAT does not support file object"
                                   " deletion: %s" % path)
    
    # Delete each specified XNAT object.
    with qixnat.connect(config) as xnat:
        obj_lists = [xnat.expand_path(path) for path in paths]
        objs = reduce(lambda x,y: x + y, obj_lists)
        for obj in objs:
            obj.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('paths', nargs='+', metavar='PATH',
                        help="the XNAT object path(s) to delete")
    # 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('paths'), nonempty_args


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