#! /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 CAT12 VBM preprocessing script.

-c /i2bm/local/cat12-standalone/standalone/cat_standalone.sh
-s /i2bm/local/cat12-standalone
-m /i2bm/local/cat12-standalone/mcr/v93
"""


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-cat12vbm",
        description=textwrap.dedent(DOC),
        formatter_class=RawTextHelpFormatter)

    # Required arguments
    required = parser.add_argument_group("required arguments")
    required.add_argument(
        "-c", "--cat12",
        required=True, metavar="<path>", type=is_file,
        help="path to the CAT12 standalone executable")
    required.add_argument(
        "-s", "--spm12",
        required=True, metavar="<path>", type=is_directory,
        help="the SPM12 folder of standalone version")
    required.add_argument(
        "-m", "--matlab",
        required=True, metavar="<path>", type=is_directory,
        help="Matlab Compiler Runtime (MCR) folder.")
    required.add_argument(
        "-a", "--anatomical",
        required=True, metavar="<path>", type=is_file, nargs="+",
        help="path to the anatomical T1w Nifti file(s).")
    required.add_argument(
        "-o", "--working_dir",
        required=True, metavar="<path>", type=is_directory,
        help="A working directory.")

    # 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)
    resource_dir = os.path.join(os.path.dirname(
        brainprep.__file__), "resources")
    kwargs["template_batch"] = os.path.join(
        resource_dir, "cat12vbm_matlabbatch.m")
    verbose = kwargs.pop("verbose")

    return kwargs, verbose


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


"""
Complete matlab batch.
"""
batch_file = os.path.join(inputs["outdir"], "cat12vbm_matlabbatch.m")
write_matlabbatch(inputs["template_batch"], inputs["anatomical"], batch_file)


"""
Launch matlab batch.
"""
cmd = [inputs["cat12"], "-s", inputs["spm12"], "-m", inputs["matlab"],
       "-b", batch_file]
brainprep.execute_command(cmd)
