#!/usr/bin/env bash
#
# PURPOSE:
#
# USAGE:
#
# INPUT:
#
# OUTPUT:
# ______________________________________________________________________
#
# Christian Gaser
# Structural Brain Mapping Group (https://neuro-jena.github.io)
# Departments of Neurology and Psychiatry
# Jena University Hospital
# ______________________________________________________________________

script_dir=$(dirname "$0")
source "${script_dir}/T1Prep_utils.sh"
out_file=""

# ----------------------------------------------------------------------
# run main
# ----------------------------------------------------------------------

main()
{
  parse_args ${1+"$@"}  
  process "$@"

  exit 0
}

# ----------------------------------------------------------------------
# check arguments and files
# ----------------------------------------------------------------------

parse_args()
{
  local optname optarg
  
  if [ $# -lt 1 ]; then
    help
    exit 1
  fi

  count=0
  while [ $# -gt 0 ]; do
    optname="${1%%=*}"
    optarg="${2:-}"

    case "$1" in
      --field)
        exit_if_empty "$optname" "$optarg"
        field=$optarg
        shift
        ;;
      --out*)
        exit_if_empty "$optname" "$optarg"
        out_file=$optarg
        shift
        ;;
      -h | --help | --h | -v | --version | -V)
        help
        exit 1
        ;;
      -*)
        echo "basename $0: ERROR: Unrecognized option \"$1\"" >&2
        exit 1
        ;;
      *)
        FILES[$count]=$1
        ((count++))
        ;;
    esac
    shift
  done

  if [[ -z "$field" || -z "$FILES" ]]; then
      help
  fi
}

# ----------------------------------------------------------------------
# process data
# ----------------------------------------------------------------------

process()
{
  # Remove existing outfile
  if [[ -n "${out_file}" && -f "${out_file}" ]]; then
    rm  "${out_file}"
  fi
  
  for f in "${FILES[@]}"; do
    # read both entries with and without values
    # supports dot-separated paths, e.g. subjectmeasures.vol_abs_CGW
    cmd=(
      jq -r --arg field "$field" '
        ($field | split(".")) as $path
        | getpath($path) as $entry
        | if $entry == null then
            "N/A"
          elif ($entry | type == "object") and ($entry | has("value")) then
            $entry.value
          else
            $entry
          end
        | if type == "array" then join(" ")
          elif type == "object" then tojson
          else tostring
          end
      ' "$f"
    )
    if [ -z "${out_file}" ]; then
      "${cmd[@]}"
    else
      "${cmd[@]}" >> "${out_file}"
    fi
  done
}


# ----------------------------------------------------------------------
# help
# ----------------------------------------------------------------------

help() {
cat << EOM
${BOLD}${BLUE}$0
---------------------------------------------${NC}

${BOLD}USAGE:${NC}
  ${GREEN}$0 [options] <json-filename(s)>${NC}

${BOLD}DESCRIPTION:${NC}

${BOLD}OPTIONS:${NC}
  --field <STR>  Field name to be used in json file.
                 Use dot notation for nested fields, e.g.
                 subjectmeasures.vol_abs_CGW
  --out <FILE>   Filename for saving the output

${BOLD}T1PREP FIELD NAMES:${NC}
  subjectmeasures                  All subject measures
  subjectmeasures.vol_TIV          Total intracranial volume (CSF+GM+WM incl. WMH)
  subjectmeasures.vol_abs_CGW      Absolute tissue volumes [CSF, GM, WM+WMH]
  subjectmeasures.vol_rel_CGW      Relative volumes [CSF, GM, WM+WMH]/TIV
  subjectmeasures.vol_WMH          WMH volume in mL
  subjectmeasures.vol_rel_WMH      WMH volume relative to WM (incl. WMH)
  qualitymeasures                  All quality measures
  

${BOLD}Author:${NC}
  Christian Gaser (christian.gaser@uni-jena.de)

EOM

}

# ----------------------------------------------------------------------
# call main program
# ----------------------------------------------------------------------

main "${@}"