```{r}
#| echo: false
#| results: 'asis'

cat('\n\n### Index Demographics\n\n')

demoList <- list(
  `Exposure Target` = targetIdsOfInterest,
  `Outcome/s` = ifelse(is.null(outcomeIdsOfInterest), NA, outcomeIdsOfInterest),
  `Indication/s` = ifelse(is.null(indicationIdsOfInterest), NA, indicationIdsOfInterest), # what about null?
  `Comparator/s` = ifelse(is.null(comparatorIdsOfInterest), NA, comparatorIdsOfInterest)
)

for(demoListInd in 1:length(demoList)){

cohortIds <- demoList[[demoListInd]]
headingName <- names(demoList)[demoListInd]

if(sum(is.na(cohortIds)) != 1){

charTargetSettings <- OhdsiReportGenerator::getCharacterizationTargetSettings(
  connectionHandler = connectionHandler,
  schema = params$schema,
  targetIds = unique(stats::na.omit(cohortIds))
)

charTargetIds <- c()
if(!is.null(charTargetSettings) && nrow(charTargetSettings) > 0){
  charTargetIds <- unique(charTargetSettings$characterizationTargetId)
}


if(length(charTargetIds) > 0){
  targetContinuousOfInterest <- OhdsiReportGenerator::getContinuousTargetBaseline(
    connectionHandler = connectionHandler,
    schema = params$schema,
    characterizationTargetIds = charTargetIds,
    analysisIds = c(2,8,9,10)
  )

  targetBinaryOfInterest <- OhdsiReportGenerator::getBinaryTargetBaseline(
    connectionHandler = connectionHandler,
    schema = params$schema,
    characterizationTargetIds = charTargetIds,
    analysisIds = c(1,2,3,4,5)
  )

  cat(paste0('\n\n#### ',headingName,' \n\n'))
  for(tId in 1:length(charTargetIds)){

    currentSetting <- charTargetSettings %>%
      dplyr::filter(.data$characterizationTargetId == !!charTargetIds[tId]) %>%
      dplyr::slice(1)

    if(nrow(currentSetting) == 0){
      next
    }

    targetMatch <- match(
      as.character(currentSetting$cohortDefinitionId[1]),
      as.character(cohortDefinitions$cohortDefinitionId)
    )

    targetFriendlyName <- as.character(currentSetting$cohortDefinitionId[1])
    targetSubsetText <- ''
    if(length(targetMatch) > 0 && !is.na(targetMatch)){
      targetFriendlyName <- cohortDefinitions$friendlyName[targetMatch]
      targetSubsetText <- cohortDefinitions$subsetText[targetMatch]
    }

# fill in the rest of the settings like in 
 boxName <- paste0(targetFriendlyName, 
            ' - ' , 
            targetSubsetText, 

   ' first exposure in ', currentSetting$limitToFirstInNDays[1], ' days ',
  'and >= ', currentSetting$minPriorObservation[1], ' days observation at index ',
  ' in nesting cohort ', currentSetting$nestingName[1], ' at index ',
  ' aged between ', currentSetting$minAge[1], ' - ', currentSetting$maxAge[1], ' at index ',
  ' study index between ', currentSetting$studyStart[1], ' to ', currentSetting$studyEnd[1], ' ',
  ' gender in ', currentSetting$genderConceptIds[1]

 )
    

    # add the target age/sex/race/ethnicity
    dataC <- targetContinuousOfInterest %>% 
      dplyr::filter(.data$characterizationTargetId == !!charTargetIds[tId]) %>%
      dplyr::select(-c("p10Value", "p25Value", "p75Value", "p90Value")) %>%
      tidyr::pivot_longer(
        cols = c("minValue","maxValue", "averageValue", "standardDeviation", "medianValue",
        )
      ) %>%
      dplyr:: mutate(
        covariateName = paste0(.data$covariateName, ' (', .data$name, ')'),
        averageValue = .data$value
      ) %>%
      dplyr::select(-dplyr::any_of(c("name", "value"))) %>%
      dplyr:: mutate(
        type = dplyr::case_when(
          .data$covariateId == 1002 ~ 'Age',
          .data$covariateId == 1008 ~ 'Prior Observation',
          .data$covariateId == 1009 ~ 'Post Observation',
          .data$covariateId == 1010 ~ 'Between Observation',
          TRUE ~ NA_character_
        )
      ) %>%
      dplyr::select("databaseName","covariateName","averageValue", "type") 
    
    
    dataB <- targetBinaryOfInterest %>% 
      dplyr::filter(.data$characterizationTargetId == !!charTargetIds[tId]) %>%
      dplyr::select("databaseName","covariateName","averageValue")
    
    dataB$type <- rep('Age Group', nrow(dataB))
    genderId <- grep('gender = ', dataB$covariateName)
    if(length(genderId) > 0){
      dataB$type[genderId] <- 'Gender'
    }
    raceId <- grep('race = ', dataB$covariateName)
    if(length(raceId) > 0){
      dataB$type[raceId] <- 'Race'
    }
    ethnicityId <- grep('ethnicity = ', dataB$covariateName)
    if(length(ethnicityId ) > 0){
      dataB$type[ethnicityId ] <- 'Ethnicity'
    }

    if(nrow(dataC) == 0 && nrow(dataB) == 0){
      next
    }
    
    # group by type and order by name
    data <- dataC %>%
      dplyr::bind_rows(dataB) 
    
    databaseCols <- unique(data$databaseName)
    
    data <- tidyr::pivot_wider(
      data = data,
      id_cols =  c("covariateName", "type"),
      names_from = "databaseName", 
      values_from = "averageValue"
    ) %>%
      dplyr::group_by(.data$type) %>%
      dplyr::arrange(.data$covariateName)
    
 
  cat('\n\n::: {.callout-note collapse="true"}')
  cat(paste0("\n# ",boxName, '\n\n'))
    
    # Render the gt table as raw HTML so Quarto does not re-process the
    # generated markup inside the callout container.
    print(
      gt::as_raw_html(
      data %>%  
        gt::gt() %>%
        gt::fmt_number(
          columns = databaseCols, # defined above 
          decimals = 2
        ) %>%
        gt::cols_label(
          covariateName = "Covariate"
        ) %>%
        gt::tab_options(
          heading.align = "left",
          data_row.padding = gt::px(7),
          column_labels.font.size = gt::px(12),
          column_labels.background.color = "#EB1800",
          column_labels.font.weight = "bold",
          row_group.background.color = "#D3D3D3",
          row_group.font.weight = "bold",
          quarto.disable_processing = TRUE
        ) %>%
        gt::tab_style(
          style = gt::cell_text(
            color = "darkgrey",
            font = gt::google_font("Source Sans Pro"),
            transform = "uppercase"
          ),
          locations = gt::cells_column_labels(gt::everything())
        ) 
    ))
    cat('\n')
    
    cat('\n\n:::\n\n')
    
  }
}

}

}

```
