# ------------------------------------------------------------------------------
# Setup
# ------------------------------------------------------------------------------

token=names(suppressWarnings(read.csv("/Users/au301842/pss_redcap_token.csv",colClasses = "character")))
uri="https://redcap.au.dk/api/"

library(REDCapR)
library(gtsummary)
source("https://raw.githubusercontent.com/agdamsbo/daDoctoR/master/R/dob_extract_cpr_function.R")

library(lubridate)

# ------------------------------------------------------------------------------
# Data download
# ------------------------------------------------------------------------------

dta <- redcap_read_oneshot(
  redcap_uri   = uri,
  token        = token,
  forms = "baggrund"
)$data |>
  mutate(kon=factor(ifelse(as.integer(substr(cpr, start = 11, stop = 11)) %%2 == 0,  # Sex determination
                           "female", "male")),
         dob=as.Date(ifelse(redcap_event_name=="inclusion_arm_1",dob_extract_cpr(cpr),NA),origin="1970-01-01"), # Date of birth
         age=trunc(time_length(difftime(indlagt,dob),"years"))) |>
  select(-c("cpr","name"))

dta<-dta[!is.na(dta$debut),]

# ------------------------------------------------------------------------------
# Table 1
# ------------------------------------------------------------------------------

vars<-c("kon","age","nihss_acute","diagnosis","psg_performed","interview")

dta|>
  tbl_summary(missing = "ifany",
              include = all_of(vars),
              missing_text="(Missing)"#,
              #label = lab_sel(labels_all,tbl1_vars)
  )|>
  add_n()|>
  as_gt() |>
  # modify with gt functions
  gt::tab_header("Baseline Characteristics") |>
  gt::tab_options(
    table.font.size = "small",
    data_row.padding = gt::px(1)) 


