#!/usr/bin/env python
"""
Sets variables (custom or otherwise) of a session or subject in a MBI-XNAT
project

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 (
    varput, __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('subject_or_session_id', type=str,
                    help="Name of subject or session to set the variable of")
parser.add_argument('variable', type=str,
                    help="Name of the variable to set")
parser.add_argument('value', help="Value of the variable")
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:
    varput(args.subject_or_session_id, args.variable, args.value,
           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)
    