#!/usr/bin/env Rscript
library(rprojroot)
library(withr)


if (!identical(getwd(), find_package_root_file())) {
  stop("This script must be run from the top directory of the shiny package")
}

if (Sys.which("yarn") == "") {
  stop("The yarn CLI must be installed and in your PATH")
}

system("yarn install")

node_dir <- find_package_root_file("node_modules/@selectize/selectize/dist")
inst_dir <- find_package_root_file("inst/www/shared/selectize")

unlink(inst_dir, recursive = TRUE)

dir.create(file.path(inst_dir, "js"), recursive = TRUE)
file.copy(
  file.path(node_dir, "js", c("selectize.js", "selectize.min.js")),
  file.path(inst_dir, "js"),
  overwrite = TRUE
)

dir.create(file.path(inst_dir, "css"), recursive = TRUE)
file.copy(
  file.path(node_dir, "css", "selectize.bootstrap3.css"),
  file.path(inst_dir, "css"),
  overwrite = TRUE
)

dir.create(file.path(inst_dir, "scss"), recursive = TRUE)
file.copy(
  file.path(node_dir, "scss"),
  inst_dir,
  overwrite = TRUE,
  recursive = TRUE
)


sanitize_scss <- function(f) {
  txt <- readLines(f)
  # Remove the unnecessary imports of Bootstrap from scss files
  txt <- txt[!grepl('@import\\s+"lib/bootstrap', txt)]
  writeLines(txt, f)
}

lapply(
  dir(file.path(inst_dir, "scss"), full.names = TRUE, recursive = TRUE),
  sanitize_scss
)


## -----------------------------------------------------------------
## Second, download accessibility plugin
## -----------------------------------------------------------------

ally_version <- "927d81e9ea86acac1724d57b2ce9f3c962fd34c4"
url <- sprintf("https://github.com/SLMNBJ/selectize-plugin-a11y/archive/%s.zip", ally_version)
dest_file <- file.path(tempdir(), paste0("selectize-plugin-a11y-", ally_version, ".zip"))
download.file(url, dest_file)

unzipped <- tempdir()
unzip(dest_file, exdir = unzipped)

dir.create(file.path(inst_dir, "accessibility", "js"), recursive = TRUE)
file.copy(
  file.path(unzipped, paste0("selectize-plugin-a11y-", ally_version), "selectize-plugin-a11y.js"),
  file.path(inst_dir, "accessibility", "js"),
  overwrite = TRUE
)


# =============================================================================
# Apply patches
# =============================================================================
# The version of selectize-plugin-a11y that we use is modified from the base version
# in the following ways:
# * In our version, each option item has their own unique id to be announced to screen readers when selection changes.

patch_dir <- find_package_root_file("tools/selectize-patches")

for (patch in list.files(patch_dir, full.names = TRUE)) {
  tryCatch(
    {
      message(sprintf("Applying %s", basename(patch)))
      with_dir(find_package_root_file(), system(sprintf("git apply %s --reject", patch)))
    },
    error = function(e) {
      quit(save = "no", status = 1)
    }
  )
}

# =============================================================================
# Add versions to files
# =============================================================================
pkg_json <- jsonlite::fromJSON(file.path(node_dir, "../package.json"))
writeLines(
  c(
    "# Generated by tools/updateSelectize.R; do not edit by hand",
    sprintf('version_selectize <- "%s"', pkg_json$version)
  ),
  find_package_root_file("R", "version_selectize.R")
)


# =============================================================================
# Generate minified js
# =============================================================================
with_dir(find_package_root_file("srcts"), system("yarn build"))
