core <- c(
  "eppoFindeR",
  "distilleR"
)

.coreUnloaded <- function() {
  search_ <- paste0("package:", core)
  
  return(core[!search_ %in% search()])
}

# Attach the package from the same package library it was loaded from before.
.sameLibrary <- function(pkg) {
  loc_ <- if (pkg %in% loadedNamespaces()) dirname(
    getNamespaceInfo(pkg, "path"))
  
  library(pkg, lib.loc = loc_, character.only = TRUE, warn.conflicts = FALSE)
}

.efsaToolsAttach <- function() {
  toLoad_ <- .coreUnloaded()
  
  suppressPackageStartupMessages(
    lapply(toLoad_, .sameLibrary)
  )
  
  invisible(toLoad_)
}

.efsaToolsAttachMessage <- function(toLoad) {
  if (length(toLoad) == 0) {
    return(NULL)
  }
  
  header_ <- cli::rule(
    left = cli::style_bold("Attaching core EFSATools packages"),
    right = paste0("EFSATools ", .packageVersionStr("EFSATools"))
  )
  
  toLoad <- sort(toLoad)
  versions_ <- vapply(toLoad, .packageVersionStr, character(1))
  
  packages_ <- paste0(
    cli::col_green(cli::symbol$tick),
    ' ',
    cli::col_blue(format(toLoad)),
    ' ',
    cli::ansi_align(versions_, max(cli::ansi_nchar(versions_)))
  )
  
  if (length(packages_) %% 2 == 1) {
    packages_ <- append(packages_, '')
  }
  col1_ <- seq_len(length(packages_) / 2)
  info_ <- paste0(packages_[col1_], "     ", packages_[-col1_])
  
  paste0(header_, '\n', paste(info_, collapse = '\n'))
}

.packageVersionStr <- function(pkg) {
  v_ <- as.character(utils::packageVersion(pkg))
  
  return(v_)
}
