version <- "1.13.2"
version_types <- "1.12.16"

jqui_folder <- rprojroot::find_package_root_file("inst", "www", "shared", "jqueryui")

tmp_zip <- tempfile(fileext = ".zip")
download.file(
  paste0("https://jqueryui.com/resources/download/jquery-ui-", version, ".zip"),
  tmp_zip
)
withr::defer(unlink(tmp_zip))

# Remove and extract
unlink(jqui_folder, recursive = TRUE)
dir.create(jqui_folder, recursive = TRUE)
print(unzip(tmp_zip, list = TRUE))
unzip(tmp_zip, exdir = jqui_folder)

dest_folder <- dir(jqui_folder, full.names = TRUE)
file.copy(
  dir(dest_folder, full.names = TRUE),
  jqui_folder,
  recursive = TRUE
)
unlink(dest_folder, recursive = TRUE)

## Clean up
# No need to keep package.json for htmlwidget
unlink(file.path(jqui_folder, "package.json"))
# The copy of jQuery that is bundled with the download, under external/, is not
# included because Shiny already has its own copy of jQuery.
unlink(file.path(jqui_folder, "external"), recursive = TRUE)


writeLines(
  c(
    "# Generated by tools/updatejQueryUI.R; do not edit by hand",
    sprintf('version_jqueryui <- "%s"', version)
  ),
  rprojroot::find_package_root_file("R", "version_jqueryui.R")
)

# Update TypeScript installation
withr::with_dir(
  rprojroot::find_package_root_file(),
  {
    exit_code <- system(paste0("yarn add @types/jqueryui@", version_types))
    if (exit_code != 0) stop("yarn could not install @types/jqueryui")
  }
)
