## Cohort Method
  
::: {style='font-size: 50%;'}

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

# for each outcome have a tab

cmSubsetIds <- c()

# panel for outcomes
cat('\n\n::: {.panel-tabset .nav-pills}')
for(outcomeId in outcomes$cohortDefinitionId){
  
  outcomeName <- outcomes$cohortFriendlyName[which(outcomes$cohortDefinitionId == outcomeId)]
  cat(paste0('\n\n### ', outcomeName))
  
  # panel for diag/table/plot
  cat('\n::::: {.panel-tabset .nav-pills}')  
  cat('\n\n#### Study Diagnostics')
  cat("\n\n:::: {.columns}")
  cat('\n\n::: {.column width="85%"} \n\n')
  
  cmTableDiag <- OhdsiReportGenerator::getCmDiagnosticsData(
    connectionHandler = connectionHandler,
    schema = resultsSchema,
    targetIds = targets$cohortDefinitionId,
    outcomeIds = outcomeId
  )
  
  if(nrow(cmTableDiag) > 0){

subsets <- cohorts %>%
filter(cohortDefinitionId %in% cmTableDiag$targetId) %>%
select("subsetDefinitionId")
cmSubsetIds <- unique(c(cmSubsetIds,subsets$subsetDefinitionId))

    
    # add table
    OhdsiReportGenerator::printReactable(
          data = cmTableDiag %>%
            dplyr::select(
              "databaseName",
              "targetName",
              "analysisId",
              "comparatorName",
              "summaryValue"
            )
          ,
          columns = list(
            databaseName = reactable::colDef(
              name = 'Database'
            ),
           targetName = reactable::colDef(
              filterable = TRUE
            ),
            comparatorName = reactable::colDef(
              filterable = TRUE
            ),
            summaryValue = reactable::colDef(
              name = "Overall Diagnostic",
              style = function(value) {
                color <- 'orange'
                if(is.na(value)){
                  color <- 'black'
                }else if(value == 'Pass'){
                  color <- '#AFE1AF'
                }else if(value == 'Fail'){
                  color <- '#E97451'
                }
                list(background = color)
              }
            )
          ), 
          defaultPageSize = defaultPageSize,
          highlight = TRUE, 
          striped = TRUE
        )
  }
  
  cat('\n\n:::')
  cat('\n::: {.column width="15%"}')
  cat('\n\n> Fail: Study failed ASSURE diagnostics')
  cat('\n\n> Pass: Study passed without warnings')
  cat('\n\n> Number: Passed wth Number of warnings')
  # end column
  cat('\n:::')
  # end columns
  cat('\n::::') 
  
  cat('\n\n#### Table Results\n\n')
  
  cmTable <- OhdsiReportGenerator::getCMEstimation(
    connectionHandler = connectionHandler,
    schema = resultsSchema,
    targetIds = targets$cohortDefinitionId,
    outcomeIds = outcomeId
  )
  
  cmMeta <- OhdsiReportGenerator::getCmMetaEstimation(
    connectionHandler = connectionHandler,
    schema = resultsSchema,
    targetIds = targets$cohortDefinitionId,
    outcomeIds = outcomeId
  )
  
  OhdsiReportGenerator::printReactable(
        data = cmTable %>% 
      dplyr::bind_rows(cmMeta) %>% 
          dplyr::select(
            'databaseName',
            'targetName',
            'comparatorName',
            'description',
            'calibratedRr',
            'calibratedCi95Lb',
            'calibratedCi95Ub',
            'calibratedOneSidedP',
            'calibratedP',
            'calibratedLogRr',
            'calibratedSeLogRr'
          ),
        columns = list(
        targetName = reactable::colDef(
            filterable = TRUE
          ),
          comparatorName = reactable::colDef(
            filterable = TRUE
          ),
          calibratedRr = reactable::colDef(
            format = reactable::colFormat(digits = 2)
          ),
          calibratedCi95Lb = reactable::colDef(
            format = reactable::colFormat(digits = 2)
          ),
          calibratedCi95Ub = reactable::colDef(
            format = reactable::colFormat(digits = 2)
          ),
          calibratedOneSidedP = reactable::colDef(
            format = reactable::colFormat(digits = 2)
          ),
          calibratedP = reactable::colDef(
            format = reactable::colFormat(digits = 2)
          ),
          calibratedLogRr = reactable::colDef(
            format = reactable::colFormat(digits = 2)
          ),
          calibratedSeLogRr = reactable::colDef(
            format = reactable::colFormat(digits = 2)
          )
        ),
        defaultPageSize = defaultPageSize,
        highlight = TRUE, 
        striped = TRUE
      )
  
  if(nrow(cmTable)>0){
    cat('\n\n#### Plot Results')
    # add Justin's nice code for cmTable
    # loop over tar
    analyses <- unique(cmTable$description)
    analysisIds <- unique(cmTable$analysisId)
    cmRes <- unique(cmTable[,c('description','analysisId', 'comparatorId')])
    
    # panel for analysis tab
    cat('\n\n::: {.panel-tabset .nav-pills}\n')
    
    for (i in seq_along(analyses)) {
      analysis <- analyses[[i]]
      analysisId <- analysisIds[[i]]
      
      cat(paste0('\n\n##### ', analysis ,'\n\n'))
      
      comps <- cmRes$comparatorId[cmRes$analysisId == analysisId]

      for(comparatorId in comps){
        cmdata <- cmTable %>% 
                dplyr::filter(
                  .data$comparatorId == !!comparatorId
                )

for(cmTargetId in unique(cmdata$targetId)){
  if(nrow(cmdata) > 0){
     cmdata <- cmdata %>% 
                dplyr::filter(
                  .data$targetId == !!cmTargetId
                )
  }
  
# adding this to handle no meta data for T and C
cmMetaT <- cmMeta %>% dplyr::filter(
                  .data$comparatorId == !!comparatorId &
                  .data$targetId == !!cmTargetId)
if(nrow(cmMetaT) == 0){
cmMetaT <- NULL
}

        
        if(nrow(cmdata) > 0 ){
          p <- tryCatch({
            OhdsiReportGenerator::plotCmEstimates(
              cmData = cmdata,
              cmMeta = cmMetaT,
              targetName = targets$cohortFriendlyName[targets$cohortDefinitionId == params$targetId],
              comparatorName = comparators$cohortFriendlyName[comparators$cohortDefinitionId == cohorts$subsetParent[cohorts$cohortDefinitionId == comparatorId]], # loop this
              selectedAnalysisId = analysisId
            )},
            error = function(e){return(as.character(e))}
          )
          
          if(!is.null(p)){
cat(paste0('\n\nFull Target Name: ', cohorts$cohortFriendlyName[cohorts$cohortDefinitionId == cmTargetId]), '\n')
cat(paste0('\nFull Comparator Name: ', cohorts$cohortFriendlyName[cohorts$cohortDefinitionId == comparatorId]), '\n\n')
            print(p)
          }
        } 
} # target
      }
    }
    # end panel for analysis tab
    cat('\n\n:::')
  }
  
  # end panel for diag/table/plot
  cat('\n\n::::')
  
} # end outcome 
# end panel for outcomes
cat('\n\n:::::')

```

:::

