## -----------------------------------------------------------------------------
library(form.model)
# Load the survey form model.
form_model_definition <- read_form_model("examples/survey/form.yaml", "form.model")
# Read the survey catalogue sources and lookup settings.
reference_configuration <- read_reference_configuration(
  system.file("examples", "survey", "references.yaml", package = "form.model"))
# Use a temporary cache for all catalogue sources in this vignette.
reference_cache_directory <- tempfile("survey-cache-")
for (catalogue in names(reference_configuration$catalogues))
  reference_configuration$catalogues[[catalogue]]$source$cache <- reference_cache_directory
# Prepare the tables and lookups required by the form model using the configured sources.
reference_preparation <- prepare_model_references(
  form_model_definition, reference_configuration)
# Display the prepared reference identifiers.
names(reference_preparation$references)

## -----------------------------------------------------------------------------
# Select the prepared station lookup.
reference_station_snapshot <- reference_preparation$references[["code_lists/stations/code"]]
# Find the canonical station row using its alias.
reference_match_rows(reference_station_snapshot, "OLD-STATION")

## -----------------------------------------------------------------------------
# Configure the installed code-list source.
reference_source_configuration <- reference_source(
  system.file("examples", "survey", "catalogue", "code_lists", package = "form.model"), reference_cache_directory
)
# Retrieve the selected code-list tables and verify their checksums.
reference_values <- get_reference_tables(c("observers", "stations"), reference_source_configuration)
# Display the selected reference rows or values.
reference_values$data$stations
# Display the selected reference rows or values.
reference_values$data$observers
# Configure the reference catalogue sources.
reference_registry_source <- reference_source(
  system.file("examples", "survey", "catalogue", "registries", package = "form.model"), reference_cache_directory
)
# Retrieve the selected reference tables and verify their checksums.
reference_registry_tables <- get_reference_tables("contacts", reference_registry_source)
# Display the selected reference rows or values.
reference_registry_tables$data$contacts$email

## -----------------------------------------------------------------------------
# Resolve reference lookups without changing the original form model.
reference_resolved_form_model <- resolve_reference_lookups(form_model_definition, reference_configuration)
# Group the downloaded tables by their configured catalogue names.
reference_catalogues <- list(code_lists = reference_values$data, registries = reference_registry_tables$data)

# Build every declared lookup using the downloaded tables.
reference_indexes <- lapply(names(reference_configuration$catalogues), function(catalogue) {
  # Read the table lookup definitions for this catalogue.
  reference_tables <- reference_configuration$catalogues[[catalogue]]$tables
  # Build the configured lookups for each table.
  lapply(names(reference_tables), function(table) {
    # Create a lookup index for each declared column.
    reference_table_lookups <- lapply(names(reference_tables[[table]]), function(column) {
      # Apply the column matching settings to the complete table.
      do.call(reference_index, c(
        list(data = reference_catalogues[[catalogue]][[table]], column = column),
        reference_tables[[table]][[column]][c("matching", "ignore_case")]
      ))
    })
    # Name the indexes after their lookup columns.
    names(reference_table_lookups) <- names(reference_tables[[table]])
    # Return the named indexes for this table.
    reference_table_lookups
  }) |> stats::setNames(names(reference_tables))
}) |> stats::setNames(names(reference_configuration$catalogues))

# Select the station-code lookup index.
reference_station_index <- reference_indexes$code_lists$stations$code
# Find the station rows matching the submitted code.
reference_station_rows <- reference_match_rows(reference_station_index, "001")
# Display the selected reference rows or values.
reference_station_index$data[reference_station_rows[[1]], , drop = FALSE]

# Select the observer-code lookup index.
reference_observer_index <- reference_indexes$code_lists$observers$code
# Find observer rows using case-insensitive comparison.
reference_observer_rows <- reference_match_rows(reference_observer_index, "alice")
# Display the selected reference rows or values.
reference_observer_index$data[reference_observer_rows[[1]], , drop = FALSE]

# Select the contact-email lookup index.
reference_email_index <- reference_indexes$registries$contacts$email
# Find contact rows matching the submitted email.
reference_email_rows <- reference_match_rows(reference_email_index, "ALICE@EXAMPLE.ORG")
# Display the selected reference rows or values.
reference_email_index$data[reference_email_rows[[1]], , drop = FALSE]

# Select the contact-name lookup index.
reference_name_index <- reference_indexes$registries$contacts$name
# Compare a reordered name and an unknown name.
reference_name_rows <- reference_match_rows(reference_name_index, c("Example Alice", "Unknown"))
# Display the number of matching rows for each submitted value.
lengths(reference_name_rows)
# Display the selected reference rows or values.
reference_name_index$data[reference_name_rows[[1]], , drop = FALSE]

## -----------------------------------------------------------------------------
# Retrieve verified tables from the local cache without contacting the source.
reference_cached_tables <- get_reference_tables(c("observers", "stations"), reference_source_configuration, offline = TRUE)
# Display the selected reference rows or values.
reference_cached_tables$data$stations$code

## -----------------------------------------------------------------------------
# Configure the reference catalogue sources.
reference_station_tables <- get_reference_tables("stations", reference_source_configuration)
# Display the selected reference rows or values.
reference_station_tables$data$stations

## ----eval=FALSE---------------------------------------------------------------
# # Locate the installed example resources.
# system.file("examples", "survey", "catalogue", "registries", package = "form.model")

## ----eval=FALSE---------------------------------------------------------------
# # Copy the installed example into the working directory.
# file.copy(
#   system.file("examples", "references.private.example.yaml", package = "form.model"),
#   "references.yaml",
#   overwrite = FALSE
# )

## ----eval=FALSE---------------------------------------------------------------
# # Install the dependency needed for this example.
# install.packages("askpass")

## ----eval=FALSE---------------------------------------------------------------
# library(form.model)
# 
# # Read the private catalogue configuration, prompting for a missing password.
# reference_private_configuration <- read_reference_configuration("references.yaml", prompt = TRUE)
# 
# # Retrieve the selected reference tables and verify their checksums.
# reference_registry_tables <- get_reference_tables("contacts", reference_private_configuration$catalogues$registries$source)
# # Display the selected reference rows or values.
# reference_registry_tables$data$contacts$email
# # "alice@example.org" "bob@example.org"

## ----eval=FALSE---------------------------------------------------------------
# # Retrieve the selected reference tables and verify their checksums.
# reference_registry_tables <- get_reference_tables(
#   "contacts", reference_private_configuration$catalogues$registries$source, offline = TRUE)
# # Display the selected reference rows or values.
# reference_registry_tables$data$contacts$email

## ----include=FALSE------------------------------------------------------------
# Remove the temporary files created by this example.
unlink(reference_cache_directory, recursive = TRUE)

