# WARNING - Generated by {fusen} from dev/flat_rename_r.Rmd: do not edit by hand

#' Industrialized file renaming
#' 
#' @param mask_filepath Character 1L. Entire file path of the excel mask
#'
#' @return No return value, called for side effects. Files are renamed
#'   on disk according to the instructions in the Excel mask.
#' 
#' @export
#' @examples
#' library(magrittr)
#' data(cars)
#' data(mtcars)
#'
#' mydir <- tempfile()
#' dir.create(mydir)
#'
#' # Two example files to rename: 
#' saveRDS(cars, file.path(mydir, "cars.rds"))
#' saveRDS(mtcars, file.path(mydir, "mtcars.rds"))
#' list.files(mydir)
#'
#' # Create the mask: 
#' mask_rename_r(input_path = mydir)
#'
#' # Fill the mask (in practice you can do it manually): 
#' mask <- rio::import(file.path(mydir, "mask_rename_r.xlsx"))
#' mask[["renamed_file"]] <- c("cars_renamed.rds", "mtcars_renamed.rds")
#' mask[["to_rename"]] <- rep(1, 2)
#' writexl::write_xlsx(mask, file.path(mydir, "mask_rename_r.xlsx"))
#'
#' # Apply the rename function: 
#' rename_r(mask_filepath = file.path(mydir, "mask_rename_r.xlsx"))
#'
#' # See the renamed files: 
#' list.files(mydir)
#'
#' # Clean tempdir: 
#' unlink(mydir, recursive = TRUE)
rename_r <- function(mask_filepath){
    
  if (! file.exists(mask_filepath)) {
    stop("mask_filepath doesn't exist. It must be a valid and full path including the xlsx file.")
  }
  
  prm <- rio::import(mask_filepath)
  
  if (! all(c("file", "renamed_file", "to_rename") %in% names(prm))) {
    stop("The mask must have the columns: file, renamed_file, to_rename")
  }
  
  prm <- prm[prm$to_rename == 1, ]
  prm[["row_number"]] <- 1:nrow(prm)
  
  mask_dir <- dirname(mask_filepath)
  errors <- character(0)

  results <- purrr::map(seq_len(nrow(prm)), \(i) {
    row <- prm[i, ]
    tryCatch({
      ok <- file.rename(
        file.path(mask_dir, row[["file"]]),
        file.path(mask_dir, row[["renamed_file"]])
      )
      if (!ok) stop("file.rename returned FALSE")
      message("Renamed: ", row[["file"]], " -> ", row[["renamed_file"]])
      TRUE
    }, error = function(e) {
      errors <<- c(errors, row[["file"]])
      warning("  Failed: ", row[["file"]], " - ", conditionMessage(e),
              call. = FALSE)
      FALSE
    })
  })

  if (length(errors) > 0) {
    warning(length(errors), " file(s) failed: ",
            paste(errors, collapse = ", "), call. = FALSE)
  }

  invisible(results)
}
