---
title: "`r params$title`"
author: "`r params$author`"
date: "`r format(Sys.time(), '%Y-%m-%d at %H:%M:%S %Z (UTC%z)')`"
output:
  pdf_document:
    toc: true
    toc_depth: 1
params:
  title: "Codebook"
  author: ""
---

```{r, eval=TRUE, echo=FALSE}

knitr::opts_chunk$set(echo = FALSE, comment="");

if (!exists('headingLevel') || !is.numeric(headingLevel) || (length(headingLevel) != 1)) {
  headingLevel <- 0;
}

```

```{r, results='asis', eval=TRUE}

codeLabels <-
  stats::setNames(x$codes$code_label, x$codes$code_id);
codeDescriptions <-
  stats::setNames(x$codes$code_description, x$codes$code_id);
codeInstructions <-
  stats::setNames(x$codes$code_instruction, x$codes$code_id);

for (currentCodeId in x$codes$code_id) {
  
  rock::heading(
    paste0(
      codeLabels[currentCodeId],
      " (code identifier: `", currentCodeId, "`)"
    ),
    headingLevel = headingLevel
  );
  
  rock::heading(
    "Description",
    headingLevel = headingLevel + 1
  );
  
  cat("\n\n",
      codeDescriptions[currentCodeId],
      "\n\n");

  rock::heading(
    "Coding instruction",
    headingLevel = headingLevel + 1
  );

  cat("\n\n",
      codeInstructions[currentCodeId],
      "\n\n");
  
  tmpDf <-
    x$examples[
      x$examples$code_id == currentCodeId,
      c("example_fragment", "core_or_edge", "hit_or_miss", "example_explanation")
    ];
  
  if (nrow(tmpDf) > 0) {
  
    rock::heading(
      "Examples",
      headingLevel = headingLevel + 1
    );
  
    cat(
      paste0(
        "\n- ",
        tmpDf[, "example_fragment"],
        " *(",
        tmpDf[, "core_or_edge"],
        " ",
        tmpDf[, "hit_or_miss"],
        "; ",
        tmpDf[, "example_explanation"],
        ")*",
        collapse = "\n"
      ),
      sep = ""
    );

  }

}

```
