#' Scorecards load metrics from verification suite
#' 
#'@description Scorecards function to load saved data files 
#'
#'@param system A vector of character strings defining the names of the 
#'  system names following the archive.yml format from verification suite. 
#'  Accepted system names: 'ECMWF-SEAS5', 'DWD-GFCS2.1', 'CMCC-SPS3.5',
#'  'ecmwfs5','Meteo-France-System 7', 'UK-MetOffice-GloSea600', 'NCEP-CFSv2'.
#'@param reference A vector of character strings defining the names of 
#'  the references following the archive.yml format from verification suite 
#'  Pending to be test with more than one. The accepted names are: 'era5'.
#'@param var A character string following the format from 
#'  variable-dictionary.yml from verification suite (TO DO: multiple variables). 
#'  The accepted names are: 'psl', 'tas', 'sfcWind', 'prlr'.
#'@param period A character string indicating the start and end years of the 
#'  reference period (e.g. '1993-2016')
#'@param start_months A vector indicating the numbers of the start months
#'@param region_name A character string indicating the name of the wider region
#'  loaded in the recipe. If no region name, can be "" or NULL.
#'@param input_path A character string indicating the path where metrics output 
#'  files from verification suite are saved (or any other compatible files)
#'
#'@return A is a list by system and reference containing an array of with 
#'   the following dimensions: longitude, latitude, forecast months, metrics, 
#'   start dates.

#'@examples
#'\dontrun{
#'loaded_metrics <- LoadMetrics(system = c('ECMWF-SEAS5','DWD-GFCS2.1'),
#'                              reference. = 'ERA5',
#'                              var = 'tas',                           
#'                              period = '1993-2016'
#'                              metric_names = c('rpss', 'crpss'),
#'                              start_months = sprintf("%02d", 1:12),
#'                              calib_method = 'raw',
#'                              region_name: 'Global',
#'                              input_path = './scorecards_data/input_data')
#'}
#'@importFrom startR Start
#'@importFrom ClimProjDiags Subset
#'@export 

LoadMetrics <- function(input_path, system, reference, var, period, metric_names,
                        start_months, region_name = NULL, calib_method = NULL) {
  
  # Initial checks
  ## system
  if (!is.character(system)) {
    stop("Parameter 'system' must be a character vector with the system names.")
  }
  ## reference
  if (!is.character(reference)) {
    stop("Parameter 'reference' must be a character vector with the reference ",
         "names.")
  }
  ## var
  if (!is.character(var)) {
    stop("Parameter 'var' must be a character vector with the var ",
         "names.")
  }
  if (length(var) > 1) {
    warning("Parameter 'var' must be of length one. Only the first value ",
            "will be used.")
    var <- var[1]
  }
  ## start_months
  if (is.character(start_months)) {
    warning("Parameter 'start_months' must be a numeric vector indicating ",
            "the starting months.")
    start_months <- as.numeric(start_months)
  }
  if (!is.numeric(start_months)) {
    stop("Parameter 'start_months' must be a numeric vector indicating ",
         "the starting months.")
  }
  if (is.null(region_name)) {
    region_name <- ""
  } else if (!is.character(region_name)) {
    warning("Parameter 'region_name' must be a character vector of the ",
            "name of the wider region.")
  } else if (length(region_name) > 1) {
    warning("Parameter 'region_name' must be of length 1. Only the first value ",
            "will be used.")
    region_name <- region_name[1]
  }
  start_months <- sprintf("%02d", start_months)
  ## input_path 
  if (!is.character(input_path)) {
    stop("Parameter 'input_path must be a character string.")
  }
  if (length(input_path) > 1) {
    input_path <- input_path[1]
    warning("Parameter 'input_path' has length greater than 1 and only the ",
            "first element will be used.")
  }
  
  ## Remove . from names
  system <- gsub('.','', system, fixed = T)
  reference <- gsub('.','', reference, fixed = T)
  
  # Load data
  ## Outer (file) dimensions: var, sdate (month), system, reference
  ## Inner dimensions: time, region
  path_pattern <-  file.path("$system$", "$reference$", calib_method,
                             region_name, var,
                             paste0("scorecards_", "$system$", "_",
                                    "$reference$", "_", var, "_$var$_",
                                    period, "_s$sdate$.nc"))
  metrics <- Start(dat = file.path(input_path, path_pattern),
                   var = metric_names,
                   system = system,
                   reference = reference,
                   sdate = start_months,
                   time = "all",
                   region = "all",
                   metadata_dims = "var",
                   return_vars = list(time = NULL,
                                      region = NULL),
                   pattern_dims = 'dat',
                   retrieve = TRUE)

  if (!is.null(attr(metrics, "NotFoundFiles"))) {
    stop("Some of the requested files were not found.")
  }

  metrics <- Subset(metrics, along = "dat",
                    indices = 1, drop = "selected")
  class(metrics) <- "array"
  return(metrics)

}
