#'Read recipe YAML file and create and store logfile info
#'
#'The purpose of this function is to read the atomic recipe generated by 
#'divide_recipe() and create its individual logfile in the output directory
#'specified in the recipe. It returns the recipe as a list with an object of
#'class logger added to it, that stores information on the workflow execution
#'and errors.
#'
#'@param recipe_file path to a YAML file with Auto-S2S configuration recipe
#'
#'@return list contaning recipe with logger, log file name and log dir name
#'
#'@import log4r
#'@import yaml
#'
#'@examples
#'setwd("/esarchive/scratch/vagudets/repos/auto-s2s/")
#'library(yaml)
#'recipe <- prepare_outputs("modules/data_load/recipe_1.yml")
#'info(recipe$Run$logger, "This is an info message")
#'
#'@export

read_atomic_recipe <- function(recipe_file) {
  # recipe_file: path to recipe YAML file
  recipe <- read_yaml(recipe_file)
  recipe$recipe_path <- recipe_file
  recipe$name <- tools::file_path_sans_ext(basename(recipe_file))
  # Create log file for atomic recipe
  logfile <- file.path(recipe$Run$output_dir, 'logs',
                       paste0(recipe$name, '.log'))
  file.create(logfile)
  # Set default behaviour of logger
  if (is.null(recipe$Run)) {
    recipe$Run <- list(Loglevel = 'INFO', Terminal = TRUE)
  }
  if (is.null(recipe$Run$Loglevel)) {
    recipe$Run$Loglevel <- 'INFO'
  }
  if (!is.logical(recipe$Run$Terminal)) {
    recipe$Run$Terminal <- TRUE
  }
  # logger set-up
  if (recipe$Run$Terminal) {
    logger <- log4r::logger(threshold = recipe$Run$Loglevel,  
                            appenders = list(console_appender(layout = default_log_layout()),
                                             file_appender(logfile, append = TRUE,   
                                                           layout = default_log_layout())))
  } else {
    logger <- log4r::logger(threshold = recipe$Run$Loglevel,
                            appenders = list(file_appender(logfile, append = TRUE,             
                                             layout = default_log_layout())))
  }
  recipe$Run$logger <- logger
  recipe$Run$logfile <- logfile
  # Restructure recipe to flatten redundant lists
  recipe <- restructure_recipe(recipe)
  return(recipe)
}
