#! /usr/bin/env python
##########################################################################
# NSAp - Copyright (C) CEA, 2013 - 2016
# 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
from __future__ import print_function
import argparse
import os
import shutil

# Bredala import
try:
    import bredala
    bredala.USE_PROFILER = False
    bredala.register("pydcmio.dcmconverter.transcoder",
                     names=["transcode_sids"])
except:
    pass

# Dcmio import
from pydcmio import __version__ as version
from pydcmio.dcmconverter.transcoder import transcode_sids

# Parameters to keep trace
__hopla__ = ["tool", "version", "inputs", "outputs", "sids", "transcode_table"]


# Script documentation
doc = """
Transcode the subject identifiers
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The transcoded subject identifier is generated randomly (12 digits random
number between 100000000000 and 999999999999). The procedure checks
if the subject identifier has already been transcoded.

Command:

python $HOME/git/pydcmio/pydcmio/scripts/pydcmio_transcode \
    -v 2 \
    -s Lola \
    -d /volatile/nsap/dcm2nii/convert \
    -o /volatile/nsap/dcm2nii/convert \
    -r /volatile/nsap/dcm2nii/transcoding_table.json
"""


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


parser = argparse.ArgumentParser(description=doc)
parser.add_argument(
    "-v", "--verbose", dest="verbose", type=int, choices=[0, 1, 2], default=0,
    help="increase the verbosity level: 0 silent, [1, 2] verbose.")
parser.add_argument(
    "-s", "--sid", dest="sid", required=False, type=str,
    help="the subject identifier.")
parser.add_argument(
    "-d", "--dir", dest="directory", required=False, metavar="PATH",
    help="a folder that contains the subject identifiers as sub folders.",
    type=is_directory)
parser.add_argument(
    "-r", "--transtable", dest="transcode_table", required=True,
    metavar="FILE", help="the transcoding table.", type=is_file)
parser.add_argument(
    "-o", "--outdir", dest="outdir", required=True, metavar="PATH",
    help="the folder that contains the generated transcoded table.",
    type=is_directory)
args = parser.parse_args()

"""
Welcome message.
"""
tool = "pydcmio_transcode"
if args.verbose > 0:
    print("[info] Start subject odentifiers transcoding...")
    print("[info] Output: {0}.".format(args.outdir))

"""
First get the subject identifiers
"""
sids = []
if args.sid is not None:
    sids.append(args.sid)
if args.directory is not None:
    sub_folders = [name for name in os.listdir(args.directory)
                   if os.path.isdir(os.path.join(args.directory, name))]
    sids.extend(sub_folders)
    sids = set(sids)
inputs = sids

"""
Then copy the input transcoding table.
"""
transcode_table = os.path.join(args.outdir,
                               os.path.basename(args.transcode_table))
shutil.copy(args.transcode_table, transcode_table)
outputs = [transcode_table]

"""
Execute the transcoding task.
"""
transcode_sids(sids, transcode_table)
if args.verbose > 1:
    print("[result] Transcoding table: {0}.".format(transcode_table))
