
#' Use a downloaded font in Shiny or Markdown
#'
#' @param id Id of the font downloaded.
#' @param css_path Path to CSS generated by \code{\link{setup_font}}.
#' @param selector CSS selector for which to use the font,
#'  usually an HTML tag, default to \code{"body"} (all document).
#' @param css CSS variables needed to use font, normally this should be automatic.
#'
#' @return an HTML tag with an HTML dependency (\code{\link[htmltools]{htmlDependency}}).
#' @export
#'
#' @importFrom glue glue_data glue
#' @importFrom htmltools tags attachDependencies htmlDependency
#' @importFrom shiny addResourcePath
#'
#' @example examples/ex-use_font.R
use_font <- function(id, css_path, selector = "body", css = NULL) {

  path <- normalizePath(path = css_path, mustWork = TRUE)
  if (!grepl(pattern = "\\.css$", x = path))
    stop("use_font: 'path' must be a CSS file!", call. = FALSE)

  selector <- paste(selector, collapse = ", ")

  if (is.null(css)) {
    css <- fonts[fonts$id == id, ]
    if (nrow(css) < 1) {
      stop("use_font: font not found, please check or provide argument CSS.", call. = FALSE)
    }
    css <- glue::glue_data(.x = css, "font-family: '{family}', {category};")
  }

  css <- glue::glue("{selector} {{{css}}}", selector = selector, css = css)
  css <- paste(css, collapse = "\n")

  shiny::addResourcePath(
    prefix = paste("gfonts", id, sep = "-"),
    directoryPath = dirname(dirname(path))
  )
  attachDependencies(
    x = tags$style(css),
    value = htmlDependency(
      name = id,
      version = "0.1.0",
      src = list(
        href = paste("gfonts", id, sep = "-"),
        file = dirname(dirname(path))
      ),
      package = NULL,
      stylesheet = file.path("css", basename(path)),
      all_files = TRUE
    )
  )
}
