#!/usr/bin/env python
"""
Uploads datasets to a MBI-XNAT project (requires manager privileges for the
project).

The format of the uploaded file is guessed from the file extension (recognised
extensions are '.nii', '.nii.gz', '.mif'), the scan entry is created in the
session and if '--create_session' option is passed the subject and session are
created if they are not already present, e.g.

    $ xnat-put TEST001_001_MR01 a_dataset --create_session test.nii.gz
    
NB: If the scan already exists the '--overwrite' option must be provided to
overwrite it.

User credentials can be stored in a ~/.netrc file so that they don't need to be
entered each time a command is run. If a new user provided or netrc doesn't
exist the tool will ask whether to create a ~/.netrc file with the given
credentials.
"""
import argparse
import re
import logging
from xnatutils import (
    put, __version__, print_response_error, print_usage_error,
    print_info_message)
from xnatutils.exceptions import XnatUtilsUsageError, XnatUtilsException
from xnat.exceptions import XNATResponseError

logger = logging.getLogger('xnat-utils')
handler = logging.StreamHandler()
handler.setLevel(logging.INFO)
formatter = logging.Formatter("%(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

parser = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('session', type=str,
                    help="Name of the session to upload the dataset to")
parser.add_argument('scan', type=str,
                    help="Name for the dataset on XNAT")
parser.add_argument('filenames', type=str, nargs='+',
                    help="Filename(s) of the dataset to upload to XNAT")
parser.add_argument('--overwrite', '-o', action='store_true', default=False,
                    help="Allow overwrite of existing dataset")
parser.add_argument('--create_session', '-c', action='store_true',
                    default=False, help=(
                        "Create the required session on XNAT to upload the "
                        "the dataset to"))
parser.add_argument('--resource', '-r', type=str, default=None,
                    help=("The name of the resource (the data format) to "
                          "upload the dataset to. If not provided the format "
                          "will be determined from the file extension (i.e. "
                          "in most cases it won't be necessary to specify"))
parser.add_argument('--user', '-u', type=str, default=None,
                    help=("The user to connect to MBI-XNAT with"))
parser.add_argument('--version', '-V', action='version',
                    version='%(prog)s ' + __version__)
parser.add_argument('--server', '-s', type=str, default=None,
                    help=("The XNAT server to connect to. If not "
                          "provided the first server found in the "
                          "~/.netrc file will be used, and if it is "
                          "empty the user will be prompted to enter an "
                          "address for the server. Multiple URLs "
                          "stored in the ~/.netrc file can be "
                          "distinguished by passing part of the URL"))
parser.add_argument('--no_netrc', '-n', action='store_true',
                    default=False,
                    help=("Don't use or store user access tokens in "
                          "~/.netrc. Useful if using a public account"))
args = parser.parse_args()

try:
    put(args.session, args.scan, *args.filenames, overwrite=args.overwrite,
        create_session=args.create_session, resource_name=args.resource,
        user=args.user, server=args.server, use_netrc=(not args.no_netrc))
except XnatUtilsUsageError as e:
    print_usage_error(e)
except XNATResponseError as e:
    print_response_error(e)
except XnatUtilsException as e:
    print_info_message(e)
    
