#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
Load freesurfer subject in freeview

@author: Brian D. Boyd, Psychiatry, Vanderbilt University
'''

import os
import sys


__copyright__ = 'Copyright 2013 Vanderbilt University. All Rights Reserved'
__exe__ = os.path.basename(__file__)
__author__ = 'Brian Boyd'
__purpose__ = "Load FreeSurfer subject in freeview"
FREEVIEW_CMD = '''freeview -v {ls_path}/mri/T1.mgz:visible=1 {ls_path}/mri/\
aparc+aseg.mgz:colormap=lut:opacity=0.7:visible=0 {ls_path}/mri/\
wm.mgz:colormap=heat:opacity=0.7:visible=1 {ls_path}/mri/\
brainmask.mgz:visible=1 -f {ls_path}/surf/\
lh.white:edgecolor=blue:edgethickness=1 {ls_path}/surf/\
lh.pial:edgecolor=red:edgethickness=1 {ls_path}/surf/\
rh.white:edgecolor=blue:edgethickness=1 {ls_path}/surf/\
rh.pial:edgecolor=red:edgethickness=1'''


def parse_args():
    """
    Method to parse arguments base on ArgumentParser

    :return: parser object parsed
    """
    from argparse import ArgumentParser
    ap = ArgumentParser(prog=__exe__, description=__purpose__)
    ap.add_argument('session', help='Session Label')
    ap.add_argument('-sd', '--subjects_dir', dest='subjects_dir',
                    help='Subjects Directory',
                    default=os.environ.get('SUBJECTS_DIR', '/tmp'))
    return ap.parse_args()


if __name__ == '__main__':
    args = parse_args()
    sess = args.session
    subjects_dir = args.subjects_dir

    local_subj_path = os.path.join(subjects_dir, sess)

    if not os.path.exists(local_subj_path):
        print('ERROR:cannot load, %s not found in local FreeSurfer subjects \
directory.' % (sess))
        sys.exit(1)

    cmd = FREEVIEW_CMD.format(ls_path=local_subj_path)

    cp_file_path = os.path.join(local_subj_path, 'tmp', 'control.dat')
    if os.path.isfile(cp_file_path):
        cmd += ' -c {}:radius=1'.format(cp_file_path)

    print('Launching freeview with command: {}'.format(cmd))
    os.system(cmd)
