#! /usr/bin/env python3
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2021
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################

# System import
import os
import argparse
import textwrap
from pprint import pprint
from datetime import datetime
from argparse import RawTextHelpFormatter
import brainprep


# Script documentation
DOC = """
The freesurfer recon-all preprocessing script.
"""

def is_file(filearg):
    """ Type for argparse - checks that file exists but does not open.
    """
    if not os.path.isfile(filearg):
        raise argparse.ArgumentError(
            "The file '{0}' does not exist!".format(filearg))
    return filearg


def is_directory(dirarg):
    """ Type for argparse - checks that directory exists.
    """
    if not os.path.isdir(dirarg):
        raise argparse.ArgumentError(
            "The directory '{0}' does not exist!".format(dirarg))
    return dirarg


def get_cmd_line_args():
    """
    Create a command line argument parser and return a dict mapping
    <argument name> -> <argument value>.
    """
    parser = argparse.ArgumentParser(
        prog="brainprep-fsreconall",
        description=textwrap.dedent(DOC),
        formatter_class=RawTextHelpFormatter)

    # Required arguments
    required = parser.add_argument_group("required arguments")
    required.add_argument(
        "-s", "--subjid",
        required=True,
        help="subject identification")
    required.add_argument(
        "-a", "--anatomical",
        required=True, metavar="<path>", type=is_file,
        help="path to the anatomical T1w Nifti file.")
    required.add_argument(
        "-o", "--outdir",
        required=True, metavar="<path>", type=is_directory,
        help="the destination folder.")

    # Optional arguments
    parser.add_argument(
        "-V", "--verbose",
        type=int, choices=[0, 1, 2], default=0,
        help="increase the verbosity level: 0 silent, [1, 2] verbose.")

    # Create a dict of arguments to pass to the 'main' function
    args = parser.parse_args()
    kwargs = vars(args)
    verbose = kwargs.pop("verbose")

    return kwargs, verbose


"""
Parse the command line.
"""
inputs, verbose = get_cmd_line_args()
runtime = {
    "tool": "brainprep-fsreconall",
    "timestamp": datetime.now().isoformat(),
    "tool_version": brainprep.__version__}
if verbose > 0:
    pprint("[info] Starting FreeSurfer recon-all preprocessing...")
    pprint("[info] Runtime:")
    pprint(runtime)
    pprint("[info] Inputs:")
    pprint(inputs)


"""
Launch freesurfer recon-all.
"""
brainprep.recon_all(
    fsdir=inputs["outdir"], anatfile=inputs["anatomical"],
    sid=inputs["subjid"], reconstruction_stage="all", resume=False,
    t2file=None, flairfile=None)
brainprep.localgi(
    fsdir=inputs["outdir"], sid=inputs["subjid"])
