# Shared helpers for the course "Statistical Methods for Modern Biology".
#
# Every chapter script (chNN_*.R) sources this file. It provides
#   * paths: CODE_DIR, COURSE_DIR, IMG_DIR, DATA_OUT (JSON for the browser demos), msmb_data(file)
#   * savefig(): writes each figure as PNG, SVG and PDF with fixed settings, so reruns give identical files
#   * export_json(): small data files read by the browser demonstrations
#   * check(), check_close(), check_summary(): helpers for the private test scripts (see README.md)
#   * theme_course(): the plotting theme used for every ggplot figure
#
# Data. Most data sets come from CRAN/Bioconductor packages. The remaining files are the data folder
# that accompanies Holmes and Huber (2019), Modern Statistics for Modern Biology. Point the environment
# variable MSMB_DATA at that folder, or place it (or a link to it) at code/msmb-data/.

suppressPackageStartupMessages({
  library(ggplot2)
  library(jsonlite)
})

CODE_DIR <- local({
  f <- tryCatch(normalizePath(sys.frame(1)$ofile), error = function(e) NA)
  if (is.na(f)) {
    a <- grep("^--file=", commandArgs(FALSE), value = TRUE)
    f <- if (length(a)) normalizePath(sub("^--file=", "", a[1])) else file.path(getwd(), "common.R")
  }
  dirname(f)
})
COURSE_DIR <- normalizePath(file.path(CODE_DIR, ".."))
IMG_DIR <- file.path(COURSE_DIR, "img")
DATA_OUT <- file.path(COURSE_DIR, "data")

MSMB_DATA <- local({
  d <- Sys.getenv("MSMB_DATA", unset = "")
  if (!nzchar(d)) d <- file.path(CODE_DIR, "msmb-data")
  d
})

msmb_data <- function(file) {
  p <- file.path(MSMB_DATA, file)
  if (!file.exists(p)) stop("data file not found: ", p,
                            "\nSet MSMB_DATA to the book's data folder (see README).", call. = FALSE)
  p
}

# Graphics devices: ragg for PNG, svglite for SVG, the built-in pdf() device for PDF (none of them
# needs X11/XQuartz). Deterministic graphics -----------------------------------------------------------------------
options(warn = 1, stringsAsFactors = FALSE)
Sys.setenv(TZ = "UTC")

theme_course <- function(base_size = 11) {
  theme_bw(base_size = base_size) +
    theme(panel.grid.minor = element_blank(),
          strip.background = element_rect(fill = "grey95", colour = "grey70"),
          legend.key = element_blank())
}
theme_set(theme_course())

COL <- c(blue = "#1f5fbf", orange = "#d9822b", green = "#2e8b57", red = "#c0392b",
         purple = "#7b4fa0", grey = "#6b7280", teal = "#14808a")

.draw <- function(p) {
  if (inherits(p, "ggplot")) print(p)
  else if (inherits(p, c("gtable", "grob", "gTree"))) { grid::grid.newpage(); grid::grid.draw(p) }
  else if (is.function(p)) p()
  else print(p)
  invisible(NULL)
}

# savefig(p, "fig-4-3", ch = 4): p is a ggplot, a grob, or a function that draws with base graphics.
# Writes img/ch04/fig-4-3.{png,svg,pdf}. Sizes are in inches.
# dense = TRUE skips the SVG (use it for plots with tens of thousands of points or raster images;
# the notes then show the PNG and offer the PDF).
savefig <- function(p, name, ch, width = 6.4, height = 4.2, dense = FALSE, res = 160) {
  dir <- file.path(IMG_DIR, sprintf("ch%02d", ch))
  dir.create(dir, recursive = TRUE, showWarnings = FALSE)
  base <- file.path(dir, name)
  set.seed(1)  # in case a geom jitters
  ragg::agg_png(paste0(base, ".png"), width = width, height = height, units = "in", res = res,
                background = "white")
  .draw(p); grDevices::dev.off()
  if (!dense) {
    set.seed(1)
    svglite::svglite(paste0(base, ".svg"), width = width, height = height, bg = "white", fix_text_size = FALSE)
    .draw(p); grDevices::dev.off()
  } else if (file.exists(paste0(base, ".svg"))) file.remove(paste0(base, ".svg"))
  set.seed(1)
  grDevices::pdf(paste0(base, ".pdf"), width = width, height = height, bg = "white", useDingbats = FALSE,
                 title = name)
  .draw(p); grDevices::dev.off()
  message("wrote ", sub(paste0(COURSE_DIR, "/"), "", base), ".{png", if (!dense) ",svg", ",pdf}")
  invisible(base)
}

# export_json(x, "ch04-mixture.json"): writes courses/biostat/data/<name>, 6 significant digits.
export_json <- function(x, name, digits = 6) {
  dir.create(DATA_OUT, recursive = TRUE, showWarnings = FALSE)
  path <- file.path(DATA_OUT, name)
  jsonlite::write_json(x, path, digits = I(digits), auto_unbox = TRUE, dataframe = "columns", na = "null")
  message("wrote data/", name, " (", format(file.size(path), big.mark = ","), " bytes)")
  invisible(path)
}

# Helpers for the private test scripts (see README.md).
.checks <- new.env()
.checks$n <- 0L; .checks$fail <- 0L
check <- function(name, ok, detail = "") {
  ok <- isTRUE(all(ok))
  .checks$n <- .checks$n + 1L
  if (!ok) .checks$fail <- .checks$fail + 1L
  cat(sprintf("%s %s%s\n", if (ok) "PASS" else "FAIL", name, if (nzchar(detail)) paste0(": ", detail) else ""))
  invisible(ok)
}
check_close <- function(name, a, b, tol = 1e-8) {
  err <- max(abs(as.numeric(a) - as.numeric(b)))
  check(name, is.finite(err) && err <= tol, sprintf("max abs diff %.2e (tol %.0e)", err, tol))
}
check_summary <- function() {
  cat(sprintf("\n%d checks, %d failed\n", .checks$n, .checks$fail))
  invisible(.checks$fail == 0L)
}

# run_figures(list(fig_4_1 = fun, ...)): runs each figure function, or only those named on the
# command line (Rscript ch04_mixtures.R fig_4_3).
run_figures <- function(figs) {
  want <- commandArgs(TRUE)
  want <- want[!grepl("^--", want)]
  todo <- if (length(want)) figs[intersect(names(figs), want)] else figs
  for (nm in names(todo)) {
    t0 <- Sys.time()
    todo[[nm]]()
    message(sprintf("  %s done in %.1fs", nm, as.numeric(difftime(Sys.time(), t0, units = "secs"))))
  }
}
