---
title: "ISAnalytics - Matrix import report"
date: "`r Sys.Date()`"
output: 
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
    theme:
      bootswatch: cosmo
      primary: "#23687A"
    navbar:
      - { title: "Website", href: "https://calabrialab.github.io/ISAnalytics/", align: right, icon: "fa-globe" }
      - { title: "GitHub", href: "https://github.com/calabrialab/ISAnalytics", align: right, icon: "fa-github" }
params:
  set_vars: null
  launch_params: null
  files_found: null
  files_imp: null
  annot_prob: null
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE)
options(DT.warn.size = FALSE)
library(flexdashboard)
library(DT)
found_color <- "#77d983"
not_found_color <- "#e36868"
secondary_col <-  "#ff9470"
proj_col <- params$set_vars$proj_col
pool_col <- params$set_vars$pool_col
launch_params <- if (is.null(params$launch_params) ||
                     purrr::is_empty(params$launch_params)) {
  NULL
} else {
    params$launch_params
  }
```

Files report {data-orientation=rows}
===============================================================================

Row1
-------------------------------------------------------------------------------
```{r}
n_proj <- length(unique(params$files_found[[proj_col]]))
n_pools <- length(unique(params$files_found[[pool_col]]))
n_anomalies <- length(params$files_found$Anomalies[
  params$files_found$Anomalies])
```

### Projects
```{r}
valueBox(value = n_proj, icon = "glyphicon-inbox")
```

### Pools
```{r}
valueBox(value = n_pools, icon = "fa-folder")
```

### Anomalies detected
```{r}
valueBox(value = n_anomalies, icon = "glyphicon-warning-sign", color = secondary_col)
```

Row2 {data-height=100}
-------------------------------------------------------------------------------
### Set arguments
```{r eval=!is.null(launch_params), results='asis'}
content <- paste0(
  c("<ul>", 
    paste0("<li><b>Chosen file patterns</b>: ", 
          paste0("'", launch_params$patterns, "'", collapse = ", "), 
          "</li>"), 
  paste0("<li><b>Matching option</b>: '", launch_params$matching_opt, "'</li>"),
  "</ul>"))
cat(content)
```

```{r eval=is.null(launch_params), results='asis'}
content <- paste("No patterns were set for this automated import operation")
cat(content)
```


Row3 {data-height=600 .tabset .tabset-fade}
-------------------------------------------------------------------------------
```{r}
collapse_file_names <- function(names) {
  if (all(is.na(names))) {
    return(NA_character_)
  }
  return(
    paste0(paste0(paste0("<b>", seq_len(length(names)), ")</b> "), 
                  names), collapse = "<br/>")
  )
}
formatted_files <- params$files_found$Files |>
  purrr::map(~ {
    .x |>
      dplyr::group_by(.data$Quantification_type) |>
      dplyr::summarise(Files_found = collapse_file_names(.data$Files_found), 
                       .groups = "drop")
  })
files_details <- purrr::map2(formatted_files, params$files_found$Files_count,
                             ~ {
                               .x |>
                                 dplyr::inner_join(.y, 
                                                   by = "Quantification_type")
                             })

count_details <- params$files_found |>
  dplyr::mutate(files_details = files_details) |>
  dplyr::select(-.data$Files, -.data$Anomalies, -.data$Files_count)  |>
  tidyr::unnest(.data$files_details) |>
  dplyr::mutate(
    !!proj_col := as.factor(.data[[proj_col]]),
    !!pool_col := as.factor(.data[[pool_col]]),
    Quantification_type = as.factor(.data$Quantification_type))
```

### Files details by quantification 
```{r}
found_render <- JS("function(data, type, row) {",
                   "var icn = ",'"\u2713"', ";",
                   "var clss = ", '"text-success"', ";",
                   "if (data == 0) {",
                   "icn = ",'"\u2715"',";",
                   "clss = ", '"text-danger"', ";",
                   "} else if (data > 1) {",
                   "icn = ",'"\u26A0"', ";",
                   "clss = ", '"text-warning"', ";",
                   "}",
                   "return '<span class='+clss+'>'+data.toString()+' '+icn+",
                   "'</span>'",
                   "}")
datatable(
  count_details, rownames = FALSE, 
  colnames = stringr::str_replace_all(colnames(count_details), "_", " "), 
  filter = 'top',
  escape = FALSE,
  options = list(
    columnDefs = list(
      list(targets = 4,
           render = found_render)
      ),
      scrollY = 350
    ),
) |> formatStyle(columns = 5, fontWeight = 'bold', textAlign = 'center')
```

### About

Summary of files found for each project/pool and quantification requested.  
If duplicated files are found you will find a 'warning' symbol next to the 
corresponding number. Please remember that in automatic mode the function
tries to discriminate between duplicates according to the provided patterns,
if no choice can be made, all files are discarded.

If no files were found for the corresponding quantification you will see a
'cross' symbol.


Import summary {data-orientation=rows}
===============================================================================

Row1
-------------------------------------------------------------------------------
```{r}
not_imported <- length(params$files_imp$Imported[
  params$files_imp$Imported == FALSE])
tot_samples <- sum(params$files_imp$Number_of_samples, na.rm = TRUE)
```

### Files not imported
```{r}
gauge(not_imported, min = 0, max = nrow(params$files_imp), 
      sectors = gaugeSectors(danger = c(1, nrow(params$files_imp))))
```

### Total samples
```{r}
valueBox(value = tot_samples)
```

Row2 {data-height=600 .tabset .tabset-fade}
-------------------------------------------------------------------------------
### Summary of files imported
```{r eval=!is.null(params$files_imp)}
files_imp <- params$files_imp |>
  dplyr::mutate(dplyr::across(c(.data[[proj_col]], 
                              .data[[pool_col]], 
                              .data$Quantification_type), .fns = as.factor))
datatable(
  files_imp,
  class = "stripe",
  filter = "top", 
  rownames = FALSE,
  colnames = stringr::str_replace_all(colnames(files_imp), "_", " "),
  options = list(
            order = list(list(4, 'asc')),
            scrollY = 350
          )
) |> formatStyle(columns = "Imported", 
              color = styleEqual(
                levels = c(TRUE, FALSE),
                values = c(found_color, not_found_color)
              ), fontWeight = "bold", textTransform = "uppercase")
```

```{r eval=is.null(params$files_imp), results='asis'}
cat("*Nothing to report*")
```

### About

Summary of files chosen for import. If `Imported` is false, something may
have gone wrong during the import phase (most likely I/O errors).

Annotation issues {data-orientation=rows}
===============================================================================

Row1 {data-height=600 .tabset .tabset-fade}
-------------------------------------------------------------------------------
### Possible annotation problems
```{r eval=!is.null(params$annot_prob)}
datatable(
  params$annot_prob,
  rownames = FALSE, 
  colnames = stringr::str_replace_all(colnames(files_details), "_", " "), 
  filter = 'top', options = list(scrollY = 350)
)
```

```{r eval=is.null(params$annot_prob), results='asis'}
cat("*Nothing to report*")
```

### About

Report on annotation issues. Here are reported, if found, integration sites that
have been annotated with 2 or more different genes. If the table isn't empty,
you might want to check your matrices or re-perform the annotation step.

Reproducibility {data-orientation=rows}
===============================================================================

Row1 {data-height=600}
-------------------------------------------------------------------------------

### Session info {style="width: 95% !important"}
```{r attr.output='style="max-height: 580px;"'}
sessionInfo()
```

