---
title: "tidyCDISC Batch Download"
output:
  pdf_document:
    toc: true
    toc_depth: 4
classoption: landscape
params:
  bds_data_: NA
  report_summary: NA
  user_notes: NA
  html_filters: NA
---

```{r setup, include=FALSE} 
knitr::opts_chunk$set(echo = FALSE, warning=FALSE, message=FALSE, progress = TRUE)
progress$inc(1) # first increment
# don't need these here, because not creating a new environment
# load in applicable packages
# library(tidyverse)
# library(plotly)
# library(knitr)
# library(rmarkdown)
# library(htmltools)
# select data from list
dat <- params$bds_data_
# some summary info, and vector of unique paramcd's
paramcds <- unique(dat$PARAMCD)
np <- length(paramcds)
# pat <- dat$USUBJID[1]
# study <- sub("\\/.*", "", dat$USUBJID[1])
print_report_summary <- !is.na(params$report_summary)
print_user_notes <- (!is.na(params$user_notes) & !rlang::is_null(params$user_notes) & params$user_notes != "")
progress$inc(1) # second increment - after libraries & light data work
```

```{r, eval=print_report_summary, results='asis'}
cat("\n## Report Summary\n")
```
```{r, eval = print_report_summary}
knitr::asis_output(params$report_summary)
```


```{r, eval = print_user_notes, results='asis'}
cat("\n## Notes\n")
```
```{r, eval = print_user_notes}
knitr::asis_output(params$user_notes)
```





## Exploratory Plots

```{r plots, results='asis', eval = TRUE, fig.height=5.3, fig.width=10}
# if fitting 2 figures to a page in portrait mode, then use fig.height = 3.6, no width
# html_filters <- gsub("</b>","",gsub("<b>","","<b>Event Lines Filtered to Include:</b><br/>&nbsp;&nbsp;&nbsp;&nbsp;Milestones: Randomization"))
html_filters <- gsub("</b>","",gsub("<b>","",params$html_filters))
filterRows <- unlist(stringr::str_split(unlist(stringr::str_split(html_filters,"<br/>")),"<br>"))
filterPrinter <- function(txt) {
  writeLines(text = txt)
  writeLines("\n")
}
  
plotter <- function(pcd){
  # Create Plot
  fn_output <- fnIndvExplVisits(
      watermark = TRUE,
      graph_output = "ggplot",
      bds_data = lb_data,
      usubjid = usubjid(),
      input_plot_hor = input$plot_hor,
      input_visit_var = input$visit_var,
      input_plot_param = pcd,
      input_plot_adam = input$plot_adam,
      input_overlay_events = input$overlay_events,
      vline_dat = vline_dat(),
      vv_dy_name = vv_dy_name()
    )
  
  
  progress$inc(1) # increment progress bar
  # cat("\n\n\\pagebreak\n")
  cat(paste("\n###",pcd,"\n"))
  print(fn_output)
  purrr::map(.x = filterRows, ~filterPrinter(txt = .x)) # print filters if they exist
  writeLines("\n")
}
# test just one plot
# print(plotter(pcd = input$plot_param))
# Use prrrr to create as many plots as their are paramcd's
tagList( #br(), br(),
  purrr::map(.x = paramcds, ~ plotter(pcd = .x))
)
progress$inc(1) # last increment
```
