# Initiate start-up file
source(file.path(rprojroot::find_root("DESCRIPTION"), "inst/startup.R"))
# Working directory requires write permission
if(file.access(".", 2) != 0){
  warning(
    "The working directory '", normalizePath("."), "' is not writable.\n",
    "Please change it to a location with write permission."
  )
}
# CRAN package, please using install.packages() to install
library(tidyr)
library(dplyr)
library(Tplyr)
library(pharmaRTF)

# Propitiatory Package, please refer appendix of ADRG to install 
library(pilot1wrappers)
options(huxtable.add_colnames = FALSE)

Step 1: Read in data

adas  <- haven::read_xpt(file.path(path$adam, "adadas.xpt")) 
adsl  <- haven::read_xpt(file.path(path$adam, "adsl.xpt")) 

Step 2: Data preparation

adas <- adas %>%
  filter(
    EFFFL == "Y",
    ITTFL=='Y',
    PARAMCD == 'ACTOT',
    ANL01FL == 'Y'
  )

Step 3: Descriptive Statistics of Endpoint Variable

t <- tplyr_table(adas, TRTP) %>% 
  set_pop_data(adsl) %>% 
  set_pop_treat_var(TRT01P) %>% 
  set_pop_where(EFFFL == "Y" & ITTFL == "Y") %>% 
  set_distinct_by(USUBJID) %>% 
  set_desc_layer_formats(
    'n' = f_str('xx', n),
    'Mean (SD)' = f_str('xx.x (xx.xx)', mean, sd),
    'Median (Range)' = f_str('xx.x (xxx;xx)', median, min, max)
  ) %>% 
  add_layer(
    group_desc(AVAL, where= AVISITN ==  0, by = "Baseline")
  ) %>% 
  add_layer(
    group_desc(AVAL, where= AVISITN == 24, by = "Week 24")
  ) %>% 
  add_layer(
    group_desc(CHG,  where= AVISITN == 24, by = "Change from Baseline")
  )
  
hdr <- adas %>% distinct(TRTP, TRTPN) %>% arrange(TRTPN) %>% pull(TRTP)
hdr_ext <- sapply(hdr, FUN = function(x) paste0("|", x, "\\line(N=**", x, "**)"), USE.NAMES = FALSE)
hdr_fin <- paste(hdr_ext, collapse = "")
# Want the header to wrap properly in the RTF file
hdr_fin <- stringr::str_replace_all(hdr_fin, "\\|Xanomeline ", "|Xanomeline\\\\line ")

sum_data <- t %>% 
  build() %>% 
  nest_rowlabels() %>% 
  select(row_label, var1_Placebo, `var1_Xanomeline Low Dose`, `var1_Xanomeline High Dose`) %>% 
  add_column_headers(

     hdr_fin,

     header_n(t)
  )

Step 4: Statistical Summaries

model_portion <- efficacy_models(adas, 'CHG', 24)

Step 5: Style the table

final <- bind_rows(sum_data, model_portion)

ht <- huxtable::as_hux(final, add_colnames = FALSE) %>%
  huxtable::set_bold(1, 1:ncol(final), TRUE) %>%
  huxtable::set_align(1, 1:ncol(final), 'center') %>%
  huxtable::set_valign(1, 1:ncol(final), 'bottom') %>%
  huxtable::set_bottom_border(1, 1:ncol(final), 1) %>%
  huxtable::set_width(1.3) %>%
  huxtable::set_escape_contents(FALSE) %>%
  huxtable::set_col_width(c(.4, .2, .2, .2))
cat(huxtable::to_screen(ht))
##                                 Placebo\line(   Xanomeline\li   Xanomeline\li  
##                                     N=79)          ne Low          ne High     
##                                                 Dose\line(N=8   Dose\line(N=7  
##                                                      1)              4)        
##  ──────────────────────────────────────────────────────────────────────────────
##    Baseline                                                                    
##    n                            79              81              74             
##    Mean (SD)                    24.1 (12.19)    24.4 (12.92)    21.3 (11.74)   
##    Median (Range)               21.0 ( 5;61)    21.0 ( 5;57)    18.0 ( 3;57)   
##    Week 24                                                                     
##    n                            79              81              74             
##    Mean (SD)                    26.7 (13.79)    26.4 (13.18)    22.8 (12.48)   
##    Median (Range)               24.0 ( 5;62)    25.0 ( 6;62)    20.0 ( 3;62)   
##    Change from Baseline                                                        
##    n                            79              81              74             
##    Mean (SD)                    2.5 ( 5.80)     2.0 ( 5.55)     1.5 ( 4.26)    
##    Median (Range)               2.0 (-11;16)    2.0 (-11;17)    1.0 ( -7;13)   
##    p-value(Dose Response)                                       0.245          
##    [1][2]                                                                      
##                                                                                
##    p-value(Xan - Placebo)                       0.569           0.233          
##    [1][3]                                                                      
##    Diff of LS Means (SE)                        -0.5 (0.82)     -1.0 (0.84)    
##    95% CI                                       (-2.1;1.1)      (-2.7;0.7)     
##                                                                                
##    p-value(Xan High - Xan                                       0.520          
##    Low) [1][3]                                                                 
##    Diff of LS Means (SE)                                        -0.5 (0.84)    
##    95% CI                                                       (-2.2;1.1)     
## 
## Column names: row_label, var1_Placebo, var1_Xanomeline Low Dose,
## var1_Xanomeline High Dose

Step 6: Write out the report

doc <- rtf_doc(ht) %>% 
  set_font_size(10) %>%
  set_ignore_cell_padding(TRUE) %>%
  set_column_header_buffer(top=1) %>% 
  add_titles(
    hf_line(
      "Protocol: CDISCPILOT01",
      "PAGE_FORMAT: Page %s of %s",
      align='split',
      bold=TRUE,
      italic=TRUE
    ),
    hf_line(
      "Population: Efficacy",
      align="left",
      bold=TRUE,
      italic=TRUE
    ),
    hf_line(
      "Table 14-3.01",
      bold=TRUE,
      italic=TRUE
    ),
    hf_line(
      "Primary Endpoint Analysis: ADAS Cog (11) - Change from Baseline to Week 24 - LOCF",
      bold=TRUE,
      italic=TRUE
    )
  ) %>% 
  add_footnotes(
    hf_line(
      "[1] Based on Analysis of covariance (ANCOVA) model with treatment and site group as factors and baseline value as a covariate.",
      align = "left",
      italic=TRUE
    ),
    hf_line(
      "[2] Test for a non-zero coefficient for treatment (dose) as a continuous variable",
      align = "left",
      italic=TRUE
    ),
    hf_line(
      "[3] Pairwise comparison with treatment as a categorical variable: p-values without adjustment for multiple comparisons.",
      align = "left",
      italic=TRUE
    ),
    hf_line(
      "FILE_PATH: Source: %s",
      "DATE_FORMAT: %H:%M %A, %B %d, %Y",
      align = "split",
      italic=TRUE
    )
  )

# Write out the RTF
write_rtf(doc, file=file.path(path$output, 'tlf-primary.rtf'))