## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  message = FALSE,
  warning = FALSE
)

## ----load-packages, message=FALSE, warning=FALSE------------------------------
library(tflmetaR)
library(gt)
library(dplyr)

## ----load-data----------------------------------------------------------------
# Load the sample metadata file included with the package
file_path <- system.file("extdata", "sample_titles.xlsx", package = "tflmetaR")

# Read the metadata from the 'footer' sheet
meta <- tflmetaR::read_tfile(filename = file_path, sheetname = "footer")

# Preview the structure of the metadata
cat("Metadata columns:", paste(names(meta), collapse = ", "))

## ----select-entry-------------------------------------------------------------
# Extract metadata components for a specific table
# Tables are identified by their TFL number (e.g., "Table 2.1")
tfl_number <- "Table 2.1"

title_info <- tflmetaR::get_title(meta, tnumber = tfl_number)
footnotes <- tflmetaR::get_footnote(meta, tnumber = tfl_number, add_footr_tstamp = FALSE)
source_info <- tflmetaR::get_source(meta, tnumber = tfl_number)
population <- tflmetaR::get_pop(meta, tnumber = tfl_number)
pgm_name <- tflmetaR::get_pgmname(meta, tnumber = tfl_number)

# Display extracted metadata
cat("Title:", unlist(title_info$TTL1), "\n")
cat("Population:", unlist(population), "\n")
cat("Program:", unlist(pgm_name), "\n")

## ----basic-table--------------------------------------------------------------
# Prepare sample data
sample_data <- mtcars |>
  head(5) |>
  select(mpg, cyl, hp, wt) |>
  mutate(across(everything(), ~ round(.x, 1)))

# Extract annotation text from metadata using [[1]] notation
main_title <- title_info$TTL1[[1]]
subtitle <- title_info$TTL2[[1]]
pop_text <- population$POPULATION[[1]]

# Extract multiple footnotes
foot1 <- footnotes$FOOT1[[1]]
foot2 <- footnotes$FOOT2[[1]]

source_text <- source_info$SOURCE[[1]]

# Create the annotated gt table
sample_data |>
  gt::gt() |>
  gt::tab_header(
    title = main_title,
    subtitle = gt::html(paste0(subtitle, "<br>", pop_text))
  ) |>
  gt::tab_footnote(
    footnote = foot1,
    locations = gt::cells_column_labels(columns = mpg)
  ) |>
  gt::tab_footnote(
    footnote = foot2,
    locations = gt::cells_column_labels(columns = cyl)
  ) |>
  gt::tab_source_note(
    source_note = paste("Source:", source_text)
  ) |>
  gt::cols_label(
    mpg = "Miles/Gallon",
    cyl = "Cylinders",
    hp = "Horsepower",
    wt = "Weight (1000 lbs)"
  ) |>
  gt::tab_options(
    table.width = gt::pct(100),
    table.font.size = gt::px(14),
    heading.title.font.size = gt::px(16),
    heading.subtitle.font.size = gt::px(14)
  )

